babylon.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var r = start.r + ((end.r - start.r) * amount);
  1781. var g = start.g + ((end.g - start.g) * amount);
  1782. var b = start.b + ((end.b - start.b) * amount);
  1783. return new Color3(r, g, b);
  1784. };
  1785. /**
  1786. * Returns a Color3 value containing a red color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Red = function () { return new Color3(1, 0, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a green color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Green = function () { return new Color3(0, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a blue color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a black color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Black = function () { return new Color3(0, 0, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a white color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.White = function () { return new Color3(1, 1, 1); };
  1810. /**
  1811. * Returns a Color3 value containing a purple color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1815. /**
  1816. * Returns a Color3 value containing a magenta color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1820. /**
  1821. * Returns a Color3 value containing a yellow color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1825. /**
  1826. * Returns a Color3 value containing a gray color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1830. /**
  1831. * Returns a Color3 value containing a teal color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1835. /**
  1836. * Returns a Color3 value containing a random color
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1840. return Color3;
  1841. }());
  1842. BABYLON.Color3 = Color3;
  1843. /**
  1844. * Class used to hold a RBGA color
  1845. */
  1846. var Color4 = /** @class */ (function () {
  1847. /**
  1848. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1849. * @param r defines the red component (between 0 and 1, default is 0)
  1850. * @param g defines the green component (between 0 and 1, default is 0)
  1851. * @param b defines the blue component (between 0 and 1, default is 0)
  1852. * @param a defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. function Color4(
  1855. /**
  1856. * Defines the red component (between 0 and 1, default is 0)
  1857. */
  1858. r,
  1859. /**
  1860. * Defines the green component (between 0 and 1, default is 0)
  1861. */
  1862. g,
  1863. /**
  1864. * Defines the blue component (between 0 and 1, default is 0)
  1865. */
  1866. b,
  1867. /**
  1868. * Defines the alpha component (between 0 and 1, default is 1)
  1869. */
  1870. a) {
  1871. if (r === void 0) { r = 0; }
  1872. if (g === void 0) { g = 0; }
  1873. if (b === void 0) { b = 0; }
  1874. if (a === void 0) { a = 1; }
  1875. this.r = r;
  1876. this.g = g;
  1877. this.b = b;
  1878. this.a = a;
  1879. }
  1880. // Operators
  1881. /**
  1882. * Adds in place the given Color4 values to the current Color4 object
  1883. * @param right defines the second operand
  1884. * @returns the current updated Color4 object
  1885. */
  1886. Color4.prototype.addInPlace = function (right) {
  1887. this.r += right.r;
  1888. this.g += right.g;
  1889. this.b += right.b;
  1890. this.a += right.a;
  1891. return this;
  1892. };
  1893. /**
  1894. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1895. * @returns the new array
  1896. */
  1897. Color4.prototype.asArray = function () {
  1898. var result = new Array();
  1899. this.toArray(result, 0);
  1900. return result;
  1901. };
  1902. /**
  1903. * Stores from the starting index in the given array the Color4 successive values
  1904. * @param array defines the array where to store the r,g,b components
  1905. * @param index defines an optional index in the target array to define where to start storing values
  1906. * @returns the current Color4 object
  1907. */
  1908. Color4.prototype.toArray = function (array, index) {
  1909. if (index === undefined) {
  1910. index = 0;
  1911. }
  1912. array[index] = this.r;
  1913. array[index + 1] = this.g;
  1914. array[index + 2] = this.b;
  1915. array[index + 3] = this.a;
  1916. return this;
  1917. };
  1918. /**
  1919. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1920. * @param right defines the second operand
  1921. * @returns a new Color4 object
  1922. */
  1923. Color4.prototype.add = function (right) {
  1924. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1925. };
  1926. /**
  1927. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1928. * @param right defines the second operand
  1929. * @returns a new Color4 object
  1930. */
  1931. Color4.prototype.subtract = function (right) {
  1932. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1933. };
  1934. /**
  1935. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1936. * @param right defines the second operand
  1937. * @param result defines the Color4 object where to store the result
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.subtractToRef = function (right, result) {
  1941. result.r = this.r - right.r;
  1942. result.g = this.g - right.g;
  1943. result.b = this.b - right.b;
  1944. result.a = this.a - right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new Color4 with the current Color4 values multiplied by scale
  1949. * @param scale defines the scaling factor to apply
  1950. * @returns a new Color4 object
  1951. */
  1952. Color4.prototype.scale = function (scale) {
  1953. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1954. };
  1955. /**
  1956. * Multiplies the current Color4 values by scale and stores the result in "result"
  1957. * @param scale defines the scaling factor to apply
  1958. * @param result defines the Color4 object where to store the result
  1959. * @returns the current unmodified Color4
  1960. */
  1961. Color4.prototype.scaleToRef = function (scale, result) {
  1962. result.r = this.r * scale;
  1963. result.g = this.g * scale;
  1964. result.b = this.b * scale;
  1965. result.a = this.a * scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Scale the current Color4 values by a factor and add the result to a given Color4
  1970. * @param scale defines the scale factor
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the unmodified current Color4
  1973. */
  1974. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1975. result.r += this.r * scale;
  1976. result.g += this.g * scale;
  1977. result.b += this.b * scale;
  1978. result.a += this.a * scale;
  1979. return this;
  1980. };
  1981. /**
  1982. * Clamps the rgb values by the min and max values and stores the result into "result"
  1983. * @param min defines minimum clamping value (default is 0)
  1984. * @param max defines maximum clamping value (default is 1)
  1985. * @param result defines color to store the result into.
  1986. * @returns the cuurent Color4
  1987. */
  1988. Color4.prototype.clampToRef = function (min, max, result) {
  1989. if (min === void 0) { min = 0; }
  1990. if (max === void 0) { max = 1; }
  1991. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1992. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1993. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1994. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1995. return this;
  1996. };
  1997. /**
  1998. * Multipy an Color4 value by another and return a new Color4 object
  1999. * @param color defines the Color4 value to multiply by
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.multiply = function (color) {
  2003. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2004. };
  2005. /**
  2006. * Multipy a Color4 value by another and push the result in a reference value
  2007. * @param color defines the Color4 value to multiply by
  2008. * @param result defines the Color4 to fill the result in
  2009. * @returns the result Color4
  2010. */
  2011. Color4.prototype.multiplyToRef = function (color, result) {
  2012. result.r = this.r * color.r;
  2013. result.g = this.g * color.g;
  2014. result.b = this.b * color.b;
  2015. result.a = this.a * color.a;
  2016. return result;
  2017. };
  2018. /**
  2019. * Creates a string with the Color4 current values
  2020. * @returns the string representation of the Color4 object
  2021. */
  2022. Color4.prototype.toString = function () {
  2023. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2024. };
  2025. /**
  2026. * Returns the string "Color4"
  2027. * @returns "Color4"
  2028. */
  2029. Color4.prototype.getClassName = function () {
  2030. return "Color4";
  2031. };
  2032. /**
  2033. * Compute the Color4 hash code
  2034. * @returns an unique number that can be used to hash Color4 objects
  2035. */
  2036. Color4.prototype.getHashCode = function () {
  2037. var hash = this.r || 0;
  2038. hash = (hash * 397) ^ (this.g || 0);
  2039. hash = (hash * 397) ^ (this.b || 0);
  2040. hash = (hash * 397) ^ (this.a || 0);
  2041. return hash;
  2042. };
  2043. /**
  2044. * Creates a new Color4 copied from the current one
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.prototype.clone = function () {
  2048. return new Color4(this.r, this.g, this.b, this.a);
  2049. };
  2050. /**
  2051. * Copies the given Color4 values into the current one
  2052. * @param source defines the source Color4 object
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.copyFrom = function (source) {
  2056. this.r = source.r;
  2057. this.g = source.g;
  2058. this.b = source.b;
  2059. this.a = source.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Copies the given float values into the current one
  2064. * @param r defines the red component to read from
  2065. * @param g defines the green component to read from
  2066. * @param b defines the blue component to read from
  2067. * @param a defines the alpha component to read from
  2068. * @returns the current updated Color4 object
  2069. */
  2070. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2071. this.r = r;
  2072. this.g = g;
  2073. this.b = b;
  2074. this.a = a;
  2075. return this;
  2076. };
  2077. /**
  2078. * Copies the given float values into the current one
  2079. * @param r defines the red component to read from
  2080. * @param g defines the green component to read from
  2081. * @param b defines the blue component to read from
  2082. * @param a defines the alpha component to read from
  2083. * @returns the current updated Color4 object
  2084. */
  2085. Color4.prototype.set = function (r, g, b, a) {
  2086. return this.copyFromFloats(r, g, b, a);
  2087. };
  2088. /**
  2089. * Compute the Color4 hexadecimal code as a string
  2090. * @returns a string containing the hexadecimal representation of the Color4 object
  2091. */
  2092. Color4.prototype.toHexString = function () {
  2093. var intR = (this.r * 255) | 0;
  2094. var intG = (this.g * 255) | 0;
  2095. var intB = (this.b * 255) | 0;
  2096. var intA = (this.a * 255) | 0;
  2097. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2098. };
  2099. /**
  2100. * Computes a new Color4 converted from the current one to linear space
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.toLinearSpace = function () {
  2104. var convertedColor = new Color4();
  2105. this.toLinearSpaceToRef(convertedColor);
  2106. return convertedColor;
  2107. };
  2108. /**
  2109. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2110. * @param convertedColor defines the Color4 object where to store the linear space version
  2111. * @returns the unmodified Color4
  2112. */
  2113. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2117. convertedColor.a = this.a;
  2118. return this;
  2119. };
  2120. /**
  2121. * Computes a new Color4 converted from the current one to gamma space
  2122. * @returns a new Color4 object
  2123. */
  2124. Color4.prototype.toGammaSpace = function () {
  2125. var convertedColor = new Color4();
  2126. this.toGammaSpaceToRef(convertedColor);
  2127. return convertedColor;
  2128. };
  2129. /**
  2130. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2131. * @param convertedColor defines the Color4 object where to store the gamma space version
  2132. * @returns the unmodified Color4
  2133. */
  2134. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2135. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2136. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2137. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2138. convertedColor.a = this.a;
  2139. return this;
  2140. };
  2141. // Statics
  2142. /**
  2143. * Creates a new Color4 from the string containing valid hexadecimal values
  2144. * @param hex defines a string containing valid hexadecimal values
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.FromHexString = function (hex) {
  2148. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2149. return new Color4(0.0, 0.0, 0.0, 0.0);
  2150. }
  2151. var r = parseInt(hex.substring(1, 3), 16);
  2152. var g = parseInt(hex.substring(3, 5), 16);
  2153. var b = parseInt(hex.substring(5, 7), 16);
  2154. var a = parseInt(hex.substring(7, 9), 16);
  2155. return Color4.FromInts(r, g, b, a);
  2156. };
  2157. /**
  2158. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.Lerp = function (left, right, amount) {
  2165. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2166. Color4.LerpToRef(left, right, amount, result);
  2167. return result;
  2168. };
  2169. /**
  2170. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2171. * @param left defines the start value
  2172. * @param right defines the end value
  2173. * @param amount defines the gradient factor
  2174. * @param result defines the Color4 object where to store data
  2175. */
  2176. Color4.LerpToRef = function (left, right, amount, result) {
  2177. result.r = left.r + (right.r - left.r) * amount;
  2178. result.g = left.g + (right.g - left.g) * amount;
  2179. result.b = left.b + (right.b - left.b) * amount;
  2180. result.a = left.a + (right.a - left.a) * amount;
  2181. };
  2182. /**
  2183. * Creates a new Color4 from the starting index element of the given array
  2184. * @param array defines the source array to read from
  2185. * @param offset defines the offset in the source array
  2186. * @returns a new Color4 object
  2187. */
  2188. Color4.FromArray = function (array, offset) {
  2189. if (offset === void 0) { offset = 0; }
  2190. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2191. };
  2192. /**
  2193. * Creates a new Color3 from integer values (< 256)
  2194. * @param r defines the red component to read from (value between 0 and 255)
  2195. * @param g defines the green component to read from (value between 0 and 255)
  2196. * @param b defines the blue component to read from (value between 0 and 255)
  2197. * @param a defines the alpha component to read from (value between 0 and 255)
  2198. * @returns a new Color3 object
  2199. */
  2200. Color4.FromInts = function (r, g, b, a) {
  2201. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2202. };
  2203. /**
  2204. * Check the content of a given array and convert it to an array containing RGBA data
  2205. * If the original array was already containing count * 4 values then it is returned directly
  2206. * @param colors defines the array to check
  2207. * @param count defines the number of RGBA data to expect
  2208. * @returns an array containing count * 4 values (RGBA)
  2209. */
  2210. Color4.CheckColors4 = function (colors, count) {
  2211. // Check if color3 was used
  2212. if (colors.length === count * 3) {
  2213. var colors4 = [];
  2214. for (var index = 0; index < colors.length; index += 3) {
  2215. var newIndex = (index / 3) * 4;
  2216. colors4[newIndex] = colors[index];
  2217. colors4[newIndex + 1] = colors[index + 1];
  2218. colors4[newIndex + 2] = colors[index + 2];
  2219. colors4[newIndex + 3] = 1.0;
  2220. }
  2221. return colors4;
  2222. }
  2223. return colors;
  2224. };
  2225. return Color4;
  2226. }());
  2227. BABYLON.Color4 = Color4;
  2228. /**
  2229. * Class representing a vector containing 2 coordinates
  2230. */
  2231. var Vector2 = /** @class */ (function () {
  2232. /**
  2233. * Creates a new Vector2 from the given x and y coordinates
  2234. * @param x defines the first coordinate
  2235. * @param y defines the second coordinate
  2236. */
  2237. function Vector2(
  2238. /** defines the first coordinate */
  2239. x,
  2240. /** defines the second coordinate */
  2241. y) {
  2242. if (x === void 0) { x = 0; }
  2243. if (y === void 0) { y = 0; }
  2244. this.x = x;
  2245. this.y = y;
  2246. }
  2247. /**
  2248. * Gets a string with the Vector2 coordinates
  2249. * @returns a string with the Vector2 coordinates
  2250. */
  2251. Vector2.prototype.toString = function () {
  2252. return "{X: " + this.x + " Y:" + this.y + "}";
  2253. };
  2254. /**
  2255. * Gets class name
  2256. * @returns the string "Vector2"
  2257. */
  2258. Vector2.prototype.getClassName = function () {
  2259. return "Vector2";
  2260. };
  2261. /**
  2262. * Gets current vector hash code
  2263. * @returns the Vector2 hash code as a number
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2273. * @param array defines the source array
  2274. * @param index defines the offset in source array
  2275. * @returns the current Vector2
  2276. */
  2277. Vector2.prototype.toArray = function (array, index) {
  2278. if (index === void 0) { index = 0; }
  2279. array[index] = this.x;
  2280. array[index + 1] = this.y;
  2281. return this;
  2282. };
  2283. /**
  2284. * Copy the current vector to an array
  2285. * @returns a new array with 2 elements: the Vector2 coordinates.
  2286. */
  2287. Vector2.prototype.asArray = function () {
  2288. var result = new Array();
  2289. this.toArray(result, 0);
  2290. return result;
  2291. };
  2292. /**
  2293. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2294. * @param source defines the source Vector2
  2295. * @returns the current updated Vector2
  2296. */
  2297. Vector2.prototype.copyFrom = function (source) {
  2298. this.x = source.x;
  2299. this.y = source.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Sets the Vector2 coordinates with the given floats
  2304. * @param x defines the first coordinate
  2305. * @param y defines the second coordinate
  2306. * @returns the current updated Vector2
  2307. */
  2308. Vector2.prototype.copyFromFloats = function (x, y) {
  2309. this.x = x;
  2310. this.y = y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given floats
  2315. * @param x defines the first coordinate
  2316. * @param y defines the second coordinate
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.set = function (x, y) {
  2320. return this.copyFromFloats(x, y);
  2321. };
  2322. /**
  2323. * Add another vector with the current one
  2324. * @param otherVector defines the other vector
  2325. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2326. */
  2327. Vector2.prototype.add = function (otherVector) {
  2328. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2332. * @param otherVector defines the other vector
  2333. * @param result defines the target vector
  2334. * @returns the unmodified current Vector2
  2335. */
  2336. Vector2.prototype.addToRef = function (otherVector, result) {
  2337. result.x = this.x + otherVector.x;
  2338. result.y = this.y + otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2343. * @param otherVector defines the other vector
  2344. * @returns the current updated Vector2
  2345. */
  2346. Vector2.prototype.addInPlace = function (otherVector) {
  2347. this.x += otherVector.x;
  2348. this.y += otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns a new Vector2
  2355. */
  2356. Vector2.prototype.addVector3 = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2361. * @param otherVector defines the other vector
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.subtract = function (otherVector) {
  2365. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2366. };
  2367. /**
  2368. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2369. * @param otherVector defines the other vector
  2370. * @param result defines the target vector
  2371. * @returns the unmodified current Vector2
  2372. */
  2373. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2374. result.x = this.x - otherVector.x;
  2375. result.y = this.y - otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @returns the current updated Vector2
  2382. */
  2383. Vector2.prototype.subtractInPlace = function (otherVector) {
  2384. this.x -= otherVector.x;
  2385. this.y -= otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Multiplies in place the current Vector2 coordinates by the given ones
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2394. this.x *= otherVector.x;
  2395. this.y *= otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.multiply = function (otherVector) {
  2404. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2405. };
  2406. /**
  2407. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2413. result.x = this.x * otherVector.x;
  2414. result.y = this.y * otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2419. * @param x defines the first coordinate
  2420. * @param y defines the second coordinate
  2421. * @returns a new Vector2
  2422. */
  2423. Vector2.prototype.multiplyByFloats = function (x, y) {
  2424. return new Vector2(this.x * x, this.y * y);
  2425. };
  2426. /**
  2427. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2428. * @param otherVector defines the other vector
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.divide = function (otherVector) {
  2432. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2433. };
  2434. /**
  2435. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @param result defines the target vector
  2438. * @returns the unmodified current Vector2
  2439. */
  2440. Vector2.prototype.divideToRef = function (otherVector, result) {
  2441. result.x = this.x / otherVector.x;
  2442. result.y = this.y / otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Divides the current Vector2 coordinates by the given ones
  2447. * @param otherVector defines the other vector
  2448. * @returns the current updated Vector2
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Gets a new Vector2 with current Vector2 negated coordinates
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.negate = function () {
  2458. return new Vector2(-this.x, -this.y);
  2459. };
  2460. /**
  2461. * Multiply the Vector2 coordinates by scale
  2462. * @param scale defines the scaling factor
  2463. * @returns the current updated Vector2
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2472. * @param scale defines the scaling factor
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.scale = function (scale) {
  2476. var result = new Vector2(0, 0);
  2477. this.scaleToRef(scale, result);
  2478. return result;
  2479. };
  2480. /**
  2481. * Scale the current Vector2 values by a factor to a given Vector2
  2482. * @param scale defines the scale factor
  2483. * @param result defines the Vector2 object where to store the result
  2484. * @returns the unmodified current Vector2
  2485. */
  2486. Vector2.prototype.scaleToRef = function (scale, result) {
  2487. result.x = this.x * scale;
  2488. result.y = this.y * scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2493. * @param scale defines the scale factor
  2494. * @param result defines the Vector2 object where to store the result
  2495. * @returns the unmodified current Vector2
  2496. */
  2497. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2498. result.x += this.x * scale;
  2499. result.y += this.y * scale;
  2500. return this;
  2501. };
  2502. /**
  2503. * Gets a boolean if two vectors are equals
  2504. * @param otherVector defines the other vector
  2505. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Gets a boolean if two vectors are equals (using an epsilon value)
  2512. * @param otherVector defines the other vector
  2513. * @param epsilon defines the minimal distance to consider equality
  2514. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2515. */
  2516. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2517. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2518. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2519. };
  2520. /**
  2521. * Gets a new Vector2 from current Vector2 floored values
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.prototype.floor = function () {
  2525. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2526. };
  2527. /**
  2528. * Gets a new Vector2 from current Vector2 floored values
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.fract = function () {
  2532. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2533. };
  2534. // Properties
  2535. /**
  2536. * Gets the length of the vector
  2537. * @returns the vector length (float)
  2538. */
  2539. Vector2.prototype.length = function () {
  2540. return Math.sqrt(this.x * this.x + this.y * this.y);
  2541. };
  2542. /**
  2543. * Gets the vector squared length
  2544. * @returns the vector squared length (float)
  2545. */
  2546. Vector2.prototype.lengthSquared = function () {
  2547. return (this.x * this.x + this.y * this.y);
  2548. };
  2549. // Methods
  2550. /**
  2551. * Normalize the vector
  2552. * @returns the current updated Vector2
  2553. */
  2554. Vector2.prototype.normalize = function () {
  2555. var len = this.length();
  2556. if (len === 0)
  2557. return this;
  2558. var num = 1.0 / len;
  2559. this.x *= num;
  2560. this.y *= num;
  2561. return this;
  2562. };
  2563. /**
  2564. * Gets a new Vector2 copied from the Vector2
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.prototype.clone = function () {
  2568. return new Vector2(this.x, this.y);
  2569. };
  2570. // Statics
  2571. /**
  2572. * Gets a new Vector2(0, 0)
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.Zero = function () {
  2576. return new Vector2(0, 0);
  2577. };
  2578. /**
  2579. * Gets a new Vector2(1, 1)
  2580. * @returns a new Vector2
  2581. */
  2582. Vector2.One = function () {
  2583. return new Vector2(1, 1);
  2584. };
  2585. /**
  2586. * Gets a new Vector2 set from the given index element of the given array
  2587. * @param array defines the data source
  2588. * @param offset defines the offset in the data source
  2589. * @returns a new Vector2
  2590. */
  2591. Vector2.FromArray = function (array, offset) {
  2592. if (offset === void 0) { offset = 0; }
  2593. return new Vector2(array[offset], array[offset + 1]);
  2594. };
  2595. /**
  2596. * Sets "result" from the given index element of the given array
  2597. * @param array defines the data source
  2598. * @param offset defines the offset in the data source
  2599. * @param result defines the target vector
  2600. */
  2601. Vector2.FromArrayToRef = function (array, offset, result) {
  2602. result.x = array[offset];
  2603. result.y = array[offset + 1];
  2604. };
  2605. /**
  2606. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2607. * @param value1 defines 1st point of control
  2608. * @param value2 defines 2nd point of control
  2609. * @param value3 defines 3rd point of control
  2610. * @param value4 defines 4th point of control
  2611. * @param amount defines the interpolation factor
  2612. * @returns a new Vector2
  2613. */
  2614. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2615. var squared = amount * amount;
  2616. var cubed = amount * squared;
  2617. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2618. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2619. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2620. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2621. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2622. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2623. return new Vector2(x, y);
  2624. };
  2625. /**
  2626. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2627. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2628. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2629. * @param value defines the value to clamp
  2630. * @param min defines the lower limit
  2631. * @param max defines the upper limit
  2632. * @returns a new Vector2
  2633. */
  2634. Vector2.Clamp = function (value, min, max) {
  2635. var x = value.x;
  2636. x = (x > max.x) ? max.x : x;
  2637. x = (x < min.x) ? min.x : x;
  2638. var y = value.y;
  2639. y = (y > max.y) ? max.y : y;
  2640. y = (y < min.y) ? min.y : y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2645. * @param value1 defines the 1st control point
  2646. * @param tangent1 defines the outgoing tangent
  2647. * @param value2 defines the 2nd control point
  2648. * @param tangent2 defines the incoming tangent
  2649. * @param amount defines the interpolation factor
  2650. * @returns a new Vector2
  2651. */
  2652. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2653. var squared = amount * amount;
  2654. var cubed = amount * squared;
  2655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2657. var part3 = (cubed - (2.0 * squared)) + amount;
  2658. var part4 = cubed - squared;
  2659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2665. * @param start defines the start vector
  2666. * @param end defines the end vector
  2667. * @param amount defines the interpolation factor
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Lerp = function (start, end, amount) {
  2671. var x = start.x + ((end.x - start.x) * amount);
  2672. var y = start.y + ((end.y - start.y) * amount);
  2673. return new Vector2(x, y);
  2674. };
  2675. /**
  2676. * Gets the dot product of the vector "left" and the vector "right"
  2677. * @param left defines first vector
  2678. * @param right defines second vector
  2679. * @returns the dot product (float)
  2680. */
  2681. Vector2.Dot = function (left, right) {
  2682. return left.x * right.x + left.y * right.y;
  2683. };
  2684. /**
  2685. * Returns a new Vector2 equal to the normalized given vector
  2686. * @param vector defines the vector to normalize
  2687. * @returns a new Vector2
  2688. */
  2689. Vector2.Normalize = function (vector) {
  2690. var newVector = vector.clone();
  2691. newVector.normalize();
  2692. return newVector;
  2693. };
  2694. /**
  2695. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2696. * @param left defines 1st vector
  2697. * @param right defines 2nd vector
  2698. * @returns a new Vector2
  2699. */
  2700. Vector2.Minimize = function (left, right) {
  2701. var x = (left.x < right.x) ? left.x : right.x;
  2702. var y = (left.y < right.y) ? left.y : right.y;
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2707. * @param left defines 1st vector
  2708. * @param right defines 2nd vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Maximize = function (left, right) {
  2712. var x = (left.x > right.x) ? left.x : right.x;
  2713. var y = (left.y > right.y) ? left.y : right.y;
  2714. return new Vector2(x, y);
  2715. };
  2716. /**
  2717. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2718. * @param vector defines the vector to transform
  2719. * @param transformation defines the matrix to apply
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Transform = function (vector, transformation) {
  2723. var r = Vector2.Zero();
  2724. Vector2.TransformToRef(vector, transformation, r);
  2725. return r;
  2726. };
  2727. /**
  2728. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2729. * @param vector defines the vector to transform
  2730. * @param transformation defines the matrix to apply
  2731. * @param result defines the target vector
  2732. */
  2733. Vector2.TransformToRef = function (vector, transformation, result) {
  2734. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2735. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2736. result.x = x;
  2737. result.y = y;
  2738. };
  2739. /**
  2740. * Determines if a given vector is included in a triangle
  2741. * @param p defines the vector to test
  2742. * @param p0 defines 1st triangle point
  2743. * @param p1 defines 2nd triangle point
  2744. * @param p2 defines 3rd triangle point
  2745. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2746. */
  2747. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2748. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2749. var sign = a < 0 ? -1 : 1;
  2750. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2751. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2752. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2753. };
  2754. /**
  2755. * Gets the distance between the vectors "value1" and "value2"
  2756. * @param value1 defines first vector
  2757. * @param value2 defines second vector
  2758. * @returns the distance between vectors
  2759. */
  2760. Vector2.Distance = function (value1, value2) {
  2761. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2762. };
  2763. /**
  2764. * Returns the squared distance between the vectors "value1" and "value2"
  2765. * @param value1 defines first vector
  2766. * @param value2 defines second vector
  2767. * @returns the squared distance between vectors
  2768. */
  2769. Vector2.DistanceSquared = function (value1, value2) {
  2770. var x = value1.x - value2.x;
  2771. var y = value1.y - value2.y;
  2772. return (x * x) + (y * y);
  2773. };
  2774. /**
  2775. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2776. * @param value1 defines first vector
  2777. * @param value2 defines second vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Center = function (value1, value2) {
  2781. var center = value1.add(value2);
  2782. center.scaleInPlace(0.5);
  2783. return center;
  2784. };
  2785. /**
  2786. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2787. * @param p defines the middle point
  2788. * @param segA defines one point of the segment
  2789. * @param segB defines the other point of the segment
  2790. * @returns the shortest distance
  2791. */
  2792. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2793. var l2 = Vector2.DistanceSquared(segA, segB);
  2794. if (l2 === 0.0) {
  2795. return Vector2.Distance(p, segA);
  2796. }
  2797. var v = segB.subtract(segA);
  2798. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2799. var proj = segA.add(v.multiplyByFloats(t, t));
  2800. return Vector2.Distance(p, proj);
  2801. };
  2802. return Vector2;
  2803. }());
  2804. BABYLON.Vector2 = Vector2;
  2805. /**
  2806. * Classed used to store (x,y,z) vector representation
  2807. * A Vector3 is the main object used in 3D geometry
  2808. * It can represent etiher the coordinates of a point the space, either a direction
  2809. * Reminder: Babylon.js uses a left handed forward facing system
  2810. */
  2811. var Vector3 = /** @class */ (function () {
  2812. /**
  2813. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2814. * @param x defines the first coordinates (on X axis)
  2815. * @param y defines the second coordinates (on Y axis)
  2816. * @param z defines the third coordinates (on Z axis)
  2817. */
  2818. function Vector3(
  2819. /**
  2820. * Defines the first coordinates (on X axis)
  2821. */
  2822. x,
  2823. /**
  2824. * Defines the second coordinates (on Y axis)
  2825. */
  2826. y,
  2827. /**
  2828. * Defines the third coordinates (on Z axis)
  2829. */
  2830. z) {
  2831. if (x === void 0) { x = 0; }
  2832. if (y === void 0) { y = 0; }
  2833. if (z === void 0) { z = 0; }
  2834. this.x = x;
  2835. this.y = y;
  2836. this.z = z;
  2837. }
  2838. /**
  2839. * Creates a string representation of the Vector3
  2840. * @returns a string with the Vector3 coordinates.
  2841. */
  2842. Vector3.prototype.toString = function () {
  2843. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2844. };
  2845. /**
  2846. * Gets the class name
  2847. * @returns the string "Vector3"
  2848. */
  2849. Vector3.prototype.getClassName = function () {
  2850. return "Vector3";
  2851. };
  2852. /**
  2853. * Creates the Vector3 hash code
  2854. * @returns a number which tends to be unique between Vector3 instances
  2855. */
  2856. Vector3.prototype.getHashCode = function () {
  2857. var hash = this.x || 0;
  2858. hash = (hash * 397) ^ (this.y || 0);
  2859. hash = (hash * 397) ^ (this.z || 0);
  2860. return hash;
  2861. };
  2862. // Operators
  2863. /**
  2864. * Creates an array containing three elements : the coordinates of the Vector3
  2865. * @returns a new array of numbers
  2866. */
  2867. Vector3.prototype.asArray = function () {
  2868. var result = [];
  2869. this.toArray(result, 0);
  2870. return result;
  2871. };
  2872. /**
  2873. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2874. * @param array defines the destination array
  2875. * @param index defines the offset in the destination array
  2876. * @returns the current Vector3
  2877. */
  2878. Vector3.prototype.toArray = function (array, index) {
  2879. if (index === void 0) { index = 0; }
  2880. array[index] = this.x;
  2881. array[index + 1] = this.y;
  2882. array[index + 2] = this.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2887. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2888. */
  2889. Vector3.prototype.toQuaternion = function () {
  2890. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2891. };
  2892. /**
  2893. * Adds the given vector to the current Vector3
  2894. * @param otherVector defines the second operand
  2895. * @returns the current updated Vector3
  2896. */
  2897. Vector3.prototype.addInPlace = function (otherVector) {
  2898. this.x += otherVector.x;
  2899. this.y += otherVector.y;
  2900. this.z += otherVector.z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2905. * @param otherVector defines the second operand
  2906. * @returns the resulting Vector3
  2907. */
  2908. Vector3.prototype.add = function (otherVector) {
  2909. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2910. };
  2911. /**
  2912. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2913. * @param otherVector defines the second operand
  2914. * @param result defines the Vector3 object where to store the result
  2915. * @returns the current Vector3
  2916. */
  2917. Vector3.prototype.addToRef = function (otherVector, result) {
  2918. result.x = this.x + otherVector.x;
  2919. result.y = this.y + otherVector.y;
  2920. result.z = this.z + otherVector.z;
  2921. return this;
  2922. };
  2923. /**
  2924. * Subtract the given vector from the current Vector3
  2925. * @param otherVector defines the second operand
  2926. * @returns the current updated Vector3
  2927. */
  2928. Vector3.prototype.subtractInPlace = function (otherVector) {
  2929. this.x -= otherVector.x;
  2930. this.y -= otherVector.y;
  2931. this.z -= otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the resulting Vector3
  2938. */
  2939. Vector3.prototype.subtract = function (otherVector) {
  2940. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2941. };
  2942. /**
  2943. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2944. * @param otherVector defines the second operand
  2945. * @param result defines the Vector3 object where to store the result
  2946. * @returns the current Vector3
  2947. */
  2948. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2949. result.x = this.x - otherVector.x;
  2950. result.y = this.y - otherVector.y;
  2951. result.z = this.z - otherVector.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2956. * @param x defines the x coordinate of the operand
  2957. * @param y defines the y coordinate of the operand
  2958. * @param z defines the z coordinate of the operand
  2959. * @returns the resulting Vector3
  2960. */
  2961. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2962. return new Vector3(this.x - x, this.y - y, this.z - z);
  2963. };
  2964. /**
  2965. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2966. * @param x defines the x coordinate of the operand
  2967. * @param y defines the y coordinate of the operand
  2968. * @param z defines the z coordinate of the operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2973. result.x = this.x - x;
  2974. result.y = this.y - y;
  2975. result.z = this.z - z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2980. * @returns a new Vector3
  2981. */
  2982. Vector3.prototype.negate = function () {
  2983. return new Vector3(-this.x, -this.y, -this.z);
  2984. };
  2985. /**
  2986. * Multiplies the Vector3 coordinates by the float "scale"
  2987. * @param scale defines the multiplier factor
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.scaleInPlace = function (scale) {
  2991. this.x *= scale;
  2992. this.y *= scale;
  2993. this.z *= scale;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2998. * @param scale defines the multiplier factor
  2999. * @returns a new Vector3
  3000. */
  3001. Vector3.prototype.scale = function (scale) {
  3002. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3006. * @param scale defines the multiplier factor
  3007. * @param result defines the Vector3 object where to store the result
  3008. * @returns the current Vector3
  3009. */
  3010. Vector3.prototype.scaleToRef = function (scale, result) {
  3011. result.x = this.x * scale;
  3012. result.y = this.y * scale;
  3013. result.z = this.z * scale;
  3014. return this;
  3015. };
  3016. /**
  3017. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3018. * @param scale defines the scale factor
  3019. * @param result defines the Vector3 object where to store the result
  3020. * @returns the unmodified current Vector3
  3021. */
  3022. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3023. result.x += this.x * scale;
  3024. result.y += this.y * scale;
  3025. result.z += this.z * scale;
  3026. return this;
  3027. };
  3028. /**
  3029. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3030. * @param otherVector defines the second operand
  3031. * @returns true if both vectors are equals
  3032. */
  3033. Vector3.prototype.equals = function (otherVector) {
  3034. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3035. };
  3036. /**
  3037. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3038. * @param otherVector defines the second operand
  3039. * @param epsilon defines the minimal distance to define values as equals
  3040. * @returns true if both vectors are distant less than epsilon
  3041. */
  3042. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3043. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3044. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3045. };
  3046. /**
  3047. * Returns true if the current Vector3 coordinates equals the given floats
  3048. * @param x defines the x coordinate of the operand
  3049. * @param y defines the y coordinate of the operand
  3050. * @param z defines the z coordinate of the operand
  3051. * @returns true if both vectors are equals
  3052. */
  3053. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3054. return this.x === x && this.y === y && this.z === z;
  3055. };
  3056. /**
  3057. * Multiplies the current Vector3 coordinates by the given ones
  3058. * @param otherVector defines the second operand
  3059. * @returns the current updated Vector3
  3060. */
  3061. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3062. this.x *= otherVector.x;
  3063. this.y *= otherVector.y;
  3064. this.z *= otherVector.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3069. * @param otherVector defines the second operand
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.multiply = function (otherVector) {
  3073. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3074. };
  3075. /**
  3076. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3077. * @param otherVector defines the second operand
  3078. * @param result defines the Vector3 object where to store the result
  3079. * @returns the current Vector3
  3080. */
  3081. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3082. result.x = this.x * otherVector.x;
  3083. result.y = this.y * otherVector.y;
  3084. result.z = this.z * otherVector.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3095. return new Vector3(this.x * x, this.y * y, this.z * z);
  3096. };
  3097. /**
  3098. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.divide = function (otherVector) {
  3103. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3104. };
  3105. /**
  3106. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.divideToRef = function (otherVector, result) {
  3112. result.x = this.x / otherVector.x;
  3113. result.y = this.y / otherVector.y;
  3114. result.z = this.z / otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Divides the current Vector3 coordinates by the given ones.
  3119. * @param otherVector defines the second operand
  3120. * @returns the current updated Vector3
  3121. */
  3122. Vector3.prototype.divideInPlace = function (otherVector) {
  3123. return this.divideToRef(otherVector, this);
  3124. };
  3125. /**
  3126. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3127. * @param other defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.minimizeInPlace = function (other) {
  3131. if (other.x < this.x)
  3132. this.x = other.x;
  3133. if (other.y < this.y)
  3134. this.y = other.y;
  3135. if (other.z < this.z)
  3136. this.z = other.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3141. * @param other defines the second operand
  3142. * @returns the current updated Vector3
  3143. */
  3144. Vector3.prototype.maximizeInPlace = function (other) {
  3145. if (other.x > this.x)
  3146. this.x = other.x;
  3147. if (other.y > this.y)
  3148. this.y = other.y;
  3149. if (other.z > this.z)
  3150. this.z = other.z;
  3151. return this;
  3152. };
  3153. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3154. /**
  3155. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3156. */
  3157. get: function () {
  3158. var absX = Math.abs(this.x);
  3159. var absY = Math.abs(this.y);
  3160. if (absX !== absY) {
  3161. return true;
  3162. }
  3163. var absZ = Math.abs(this.z);
  3164. if (absX !== absZ) {
  3165. return true;
  3166. }
  3167. if (absY !== absZ) {
  3168. return true;
  3169. }
  3170. return false;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. /**
  3176. * Gets a new Vector3 from current Vector3 floored values
  3177. * @returns a new Vector3
  3178. */
  3179. Vector3.prototype.floor = function () {
  3180. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3181. };
  3182. /**
  3183. * Gets a new Vector3 from current Vector3 floored values
  3184. * @returns a new Vector3
  3185. */
  3186. Vector3.prototype.fract = function () {
  3187. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3188. };
  3189. // Properties
  3190. /**
  3191. * Gets the length of the Vector3
  3192. * @returns the length of the Vecto3
  3193. */
  3194. Vector3.prototype.length = function () {
  3195. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3196. };
  3197. /**
  3198. * Gets the squared length of the Vector3
  3199. * @returns squared length of the Vector3
  3200. */
  3201. Vector3.prototype.lengthSquared = function () {
  3202. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3203. };
  3204. /**
  3205. * Normalize the current Vector3.
  3206. * Please note that this is an in place operation.
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.normalize = function () {
  3210. var len = this.length();
  3211. if (len === 0 || len === 1.0)
  3212. return this;
  3213. var num = 1.0 / len;
  3214. this.x *= num;
  3215. this.y *= num;
  3216. this.z *= num;
  3217. return this;
  3218. };
  3219. /**
  3220. * Normalize the current Vector3 to a new vector
  3221. * @returns the new Vector3
  3222. */
  3223. Vector3.prototype.normalizeToNew = function () {
  3224. var normalized = new Vector3(0, 0, 0);
  3225. this.normalizeToRef(normalized);
  3226. return normalized;
  3227. };
  3228. /**
  3229. * Normalize the current Vector3 to the reference
  3230. * @param reference define the Vector3 to update
  3231. * @returns the updated Vector3
  3232. */
  3233. Vector3.prototype.normalizeToRef = function (reference) {
  3234. var len = this.length();
  3235. if (len === 0 || len === 1.0) {
  3236. reference.set(this.x, this.y, this.z);
  3237. return reference;
  3238. }
  3239. var scale = 1.0 / len;
  3240. this.scaleToRef(scale, reference);
  3241. return reference;
  3242. };
  3243. /**
  3244. * Creates a new Vector3 copied from the current Vector3
  3245. * @returns the new Vector3
  3246. */
  3247. Vector3.prototype.clone = function () {
  3248. return new Vector3(this.x, this.y, this.z);
  3249. };
  3250. /**
  3251. * Copies the given vector coordinates to the current Vector3 ones
  3252. * @param source defines the source Vector3
  3253. * @returns the current updated Vector3
  3254. */
  3255. Vector3.prototype.copyFrom = function (source) {
  3256. this.x = source.x;
  3257. this.y = source.y;
  3258. this.z = source.z;
  3259. return this;
  3260. };
  3261. /**
  3262. * Copies the given floats to the current Vector3 coordinates
  3263. * @param x defines the x coordinate of the operand
  3264. * @param y defines the y coordinate of the operand
  3265. * @param z defines the z coordinate of the operand
  3266. * @returns the current updated Vector3
  3267. */
  3268. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3269. this.x = x;
  3270. this.y = y;
  3271. this.z = z;
  3272. return this;
  3273. };
  3274. /**
  3275. * Copies the given floats to the current Vector3 coordinates
  3276. * @param x defines the x coordinate of the operand
  3277. * @param y defines the y coordinate of the operand
  3278. * @param z defines the z coordinate of the operand
  3279. * @returns the current updated Vector3
  3280. */
  3281. Vector3.prototype.set = function (x, y, z) {
  3282. return this.copyFromFloats(x, y, z);
  3283. };
  3284. // Statics
  3285. /**
  3286. * Get the clip factor between two vectors
  3287. * @param vector0 defines the first operand
  3288. * @param vector1 defines the second operand
  3289. * @param axis defines the axis to use
  3290. * @param size defines the size along the axis
  3291. * @returns the clip factor
  3292. */
  3293. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3294. var d0 = Vector3.Dot(vector0, axis) - size;
  3295. var d1 = Vector3.Dot(vector1, axis) - size;
  3296. var s = d0 / (d0 - d1);
  3297. return s;
  3298. };
  3299. /**
  3300. * Get angle between two vectors
  3301. * @param vector0 angle between vector0 and vector1
  3302. * @param vector1 angle between vector0 and vector1
  3303. * @param normal direction of the normal
  3304. * @return the angle between vector0 and vector1
  3305. */
  3306. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3307. var v0 = vector0.clone().normalize();
  3308. var v1 = vector1.clone().normalize();
  3309. var dot = Vector3.Dot(v0, v1);
  3310. var n = Vector3.Cross(v0, v1);
  3311. if (Vector3.Dot(n, normal) > 0) {
  3312. return Math.acos(dot);
  3313. }
  3314. return -Math.acos(dot);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set from the index "offset" of the given array
  3318. * @param array defines the source array
  3319. * @param offset defines the offset in the source array
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.FromArray = function (array, offset) {
  3323. if (!offset) {
  3324. offset = 0;
  3325. }
  3326. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3330. * This function is deprecated. Use FromArray instead
  3331. * @param array defines the source array
  3332. * @param offset defines the offset in the source array
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.FromFloatArray = function (array, offset) {
  3336. return Vector3.FromArray(array, offset);
  3337. };
  3338. /**
  3339. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3340. * @param array defines the source array
  3341. * @param offset defines the offset in the source array
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.FromArrayToRef = function (array, offset, result) {
  3345. result.x = array[offset];
  3346. result.y = array[offset + 1];
  3347. result.z = array[offset + 2];
  3348. };
  3349. /**
  3350. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArrayToRef instead.
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @param result defines the Vector3 where to store the result
  3355. */
  3356. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3357. return Vector3.FromArrayToRef(array, offset, result);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the given floats.
  3361. * @param x defines the x coordinate of the source
  3362. * @param y defines the y coordinate of the source
  3363. * @param z defines the z coordinate of the source
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3367. result.x = x;
  3368. result.y = y;
  3369. result.z = z;
  3370. };
  3371. /**
  3372. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3373. * @returns a new empty Vector3
  3374. */
  3375. Vector3.Zero = function () {
  3376. return new Vector3(0.0, 0.0, 0.0);
  3377. };
  3378. /**
  3379. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3380. * @returns a new unit Vector3
  3381. */
  3382. Vector3.One = function () {
  3383. return new Vector3(1.0, 1.0, 1.0);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3387. * @returns a new up Vector3
  3388. */
  3389. Vector3.Up = function () {
  3390. return new Vector3(0.0, 1.0, 0.0);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3394. * @returns a new down Vector3
  3395. */
  3396. Vector3.Down = function () {
  3397. return new Vector3(0.0, -1.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3401. * @returns a new forward Vector3
  3402. */
  3403. Vector3.Forward = function () {
  3404. return new Vector3(0.0, 0.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3408. * @returns a new right Vector3
  3409. */
  3410. Vector3.Right = function () {
  3411. return new Vector3(1.0, 0.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3415. * @returns a new left Vector3
  3416. */
  3417. Vector3.Left = function () {
  3418. return new Vector3(-1.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3422. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3423. * @param vector defines the Vector3 to transform
  3424. * @param transformation defines the transformation matrix
  3425. * @returns the transformed Vector3
  3426. */
  3427. Vector3.TransformCoordinates = function (vector, transformation) {
  3428. var result = Vector3.Zero();
  3429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3430. return result;
  3431. };
  3432. /**
  3433. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3443. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3444. result.x = x / w;
  3445. result.y = y / w;
  3446. result.z = z / w;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3450. * This method computes tranformed coordinates only, not transformed direction vectors
  3451. * @param x define the x coordinate of the source vector
  3452. * @param y define the y coordinate of the source vector
  3453. * @param z define the z coordinate of the source vector
  3454. * @param transformation defines the transformation matrix
  3455. * @param result defines the Vector3 where to store the result
  3456. */
  3457. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3458. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3459. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3460. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3461. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3462. result.x = rx / rw;
  3463. result.y = ry / rw;
  3464. result.z = rz / rw;
  3465. };
  3466. /**
  3467. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param vector defines the Vector3 to transform
  3470. * @param transformation defines the transformation matrix
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.TransformNormal = function (vector, transformation) {
  3474. var result = Vector3.Zero();
  3475. Vector3.TransformNormalToRef(vector, transformation, result);
  3476. return result;
  3477. };
  3478. /**
  3479. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3486. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3487. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3488. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3489. result.x = x;
  3490. result.y = y;
  3491. result.z = z;
  3492. };
  3493. /**
  3494. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3495. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3496. * @param x define the x coordinate of the source vector
  3497. * @param y define the y coordinate of the source vector
  3498. * @param z define the z coordinate of the source vector
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3503. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3504. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3505. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3506. };
  3507. /**
  3508. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3509. * @param value1 defines the first control point
  3510. * @param value2 defines the second control point
  3511. * @param value3 defines the third control point
  3512. * @param value4 defines the fourth control point
  3513. * @param amount defines the amount on the spline to use
  3514. * @returns the new Vector3
  3515. */
  3516. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3517. var squared = amount * amount;
  3518. var cubed = amount * squared;
  3519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3525. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3526. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3527. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3528. return new Vector3(x, y, z);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3532. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3533. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3534. * @param value defines the current value
  3535. * @param min defines the lower range value
  3536. * @param max defines the upper range value
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Clamp = function (value, min, max) {
  3540. var x = value.x;
  3541. x = (x > max.x) ? max.x : x;
  3542. x = (x < min.x) ? min.x : x;
  3543. var y = value.y;
  3544. y = (y > max.y) ? max.y : y;
  3545. y = (y < min.y) ? min.y : y;
  3546. var z = value.z;
  3547. z = (z > max.z) ? max.z : z;
  3548. z = (z < min.z) ? min.z : z;
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3553. * @param value1 defines the first control point
  3554. * @param tangent1 defines the first tangent vector
  3555. * @param value2 defines the second control point
  3556. * @param tangent2 defines the second tangent vector
  3557. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3561. var squared = amount * amount;
  3562. var cubed = amount * squared;
  3563. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3564. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3565. var part3 = (cubed - (2.0 * squared)) + amount;
  3566. var part4 = cubed - squared;
  3567. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3568. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3569. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3574. * @param start defines the start value
  3575. * @param end defines the end value
  3576. * @param amount max defines amount between both (between 0 and 1)
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.Lerp = function (start, end, amount) {
  3580. var result = new Vector3(0, 0, 0);
  3581. Vector3.LerpToRef(start, end, amount, result);
  3582. return result;
  3583. };
  3584. /**
  3585. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.LerpToRef = function (start, end, amount, result) {
  3592. result.x = start.x + ((end.x - start.x) * amount);
  3593. result.y = start.y + ((end.y - start.y) * amount);
  3594. result.z = start.z + ((end.z - start.z) * amount);
  3595. };
  3596. /**
  3597. * Returns the dot product (float) between the vectors "left" and "right"
  3598. * @param left defines the left operand
  3599. * @param right defines the right operand
  3600. * @returns the dot product
  3601. */
  3602. Vector3.Dot = function (left, right) {
  3603. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3604. };
  3605. /**
  3606. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3607. * The cross product is then orthogonal to both "left" and "right"
  3608. * @param left defines the left operand
  3609. * @param right defines the right operand
  3610. * @returns the cross product
  3611. */
  3612. Vector3.Cross = function (left, right) {
  3613. var result = Vector3.Zero();
  3614. Vector3.CrossToRef(left, right, result);
  3615. return result;
  3616. };
  3617. /**
  3618. * Sets the given vector "result" with the cross product of "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @param result defines the Vector3 where to store the result
  3623. */
  3624. Vector3.CrossToRef = function (left, right, result) {
  3625. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3626. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3627. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3628. result.copyFrom(MathTmp.Vector3[0]);
  3629. };
  3630. /**
  3631. * Returns a new Vector3 as the normalization of the given vector
  3632. * @param vector defines the Vector3 to normalize
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Normalize = function (vector) {
  3636. var result = Vector3.Zero();
  3637. Vector3.NormalizeToRef(vector, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the normalization of the given first vector
  3642. * @param vector defines the Vector3 to normalize
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.NormalizeToRef = function (vector, result) {
  3646. result.copyFrom(vector);
  3647. result.normalize();
  3648. };
  3649. /**
  3650. * Project a Vector3 onto screen space
  3651. * @param vector defines the Vector3 to project
  3652. * @param world defines the world matrix to use
  3653. * @param transform defines the transform (view x projection) matrix to use
  3654. * @param viewport defines the screen viewport to use
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Project = function (vector, world, transform, viewport) {
  3658. var cw = viewport.width;
  3659. var ch = viewport.height;
  3660. var cx = viewport.x;
  3661. var cy = viewport.y;
  3662. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3663. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3664. var matrix = MathTmp.Matrix[0];
  3665. world.multiplyToRef(transform, matrix);
  3666. matrix.multiplyToRef(viewportMatrix, matrix);
  3667. return Vector3.TransformCoordinates(vector, matrix);
  3668. };
  3669. /**
  3670. * Unproject from screen space to object space
  3671. * @param source defines the screen space Vector3 to use
  3672. * @param viewportWidth defines the current width of the viewport
  3673. * @param viewportHeight defines the current height of the viewport
  3674. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3675. * @param transform defines the transform (view x projection) matrix to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3679. var matrix = MathTmp.Matrix[0];
  3680. world.multiplyToRef(transform, matrix);
  3681. matrix.invert();
  3682. source.x = source.x / viewportWidth * 2 - 1;
  3683. source.y = -(source.y / viewportHeight * 2 - 1);
  3684. var vector = Vector3.TransformCoordinates(source, matrix);
  3685. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3686. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3687. vector = vector.scale(1.0 / num);
  3688. }
  3689. return vector;
  3690. };
  3691. /**
  3692. * Unproject from screen space to object space
  3693. * @param source defines the screen space Vector3 to use
  3694. * @param viewportWidth defines the current width of the viewport
  3695. * @param viewportHeight defines the current height of the viewport
  3696. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3697. * @param view defines the view matrix to use
  3698. * @param projection defines the projection matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3702. var result = Vector3.Zero();
  3703. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3704. return result;
  3705. };
  3706. /**
  3707. * Unproject from screen space to object space
  3708. * @param source defines the screen space Vector3 to use
  3709. * @param viewportWidth defines the current width of the viewport
  3710. * @param viewportHeight defines the current height of the viewport
  3711. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3712. * @param view defines the view matrix to use
  3713. * @param projection defines the projection matrix to use
  3714. * @param result defines the Vector3 where to store the result
  3715. */
  3716. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3717. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param sourceX defines the screen space x coordinate to use
  3722. * @param sourceY defines the screen space y coordinate to use
  3723. * @param sourceZ defines the screen space z coordinate to use
  3724. * @param viewportWidth defines the current width of the viewport
  3725. * @param viewportHeight defines the current height of the viewport
  3726. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3727. * @param view defines the view matrix to use
  3728. * @param projection defines the projection matrix to use
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3732. var matrix = MathTmp.Matrix[0];
  3733. world.multiplyToRef(view, matrix);
  3734. matrix.multiplyToRef(projection, matrix);
  3735. matrix.invert();
  3736. var screenSource = MathTmp.Vector3[0];
  3737. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3738. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3739. screenSource.z = 2 * sourceZ - 1.0;
  3740. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3741. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3742. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3743. result.scaleInPlace(1.0 / num);
  3744. }
  3745. };
  3746. /**
  3747. * Gets the minimal coordinate values between two Vector3
  3748. * @param left defines the first operand
  3749. * @param right defines the second operand
  3750. * @returns the new Vector3
  3751. */
  3752. Vector3.Minimize = function (left, right) {
  3753. var min = left.clone();
  3754. min.minimizeInPlace(right);
  3755. return min;
  3756. };
  3757. /**
  3758. * Gets the maximal coordinate values between two Vector3
  3759. * @param left defines the first operand
  3760. * @param right defines the second operand
  3761. * @returns the new Vector3
  3762. */
  3763. Vector3.Maximize = function (left, right) {
  3764. var max = left.clone();
  3765. max.maximizeInPlace(right);
  3766. return max;
  3767. };
  3768. /**
  3769. * Returns the distance between the vectors "value1" and "value2"
  3770. * @param value1 defines the first operand
  3771. * @param value2 defines the second operand
  3772. * @returns the distance
  3773. */
  3774. Vector3.Distance = function (value1, value2) {
  3775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3776. };
  3777. /**
  3778. * Returns the squared distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the squared distance
  3782. */
  3783. Vector3.DistanceSquared = function (value1, value2) {
  3784. var x = value1.x - value2.x;
  3785. var y = value1.y - value2.y;
  3786. var z = value1.z - value2.z;
  3787. return (x * x) + (y * y) + (z * z);
  3788. };
  3789. /**
  3790. * Returns a new Vector3 located at the center between "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the new Vector3
  3794. */
  3795. Vector3.Center = function (value1, value2) {
  3796. var center = value1.add(value2);
  3797. center.scaleInPlace(0.5);
  3798. return center;
  3799. };
  3800. /**
  3801. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3802. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3803. * to something in order to rotate it from its local system to the given target system
  3804. * Note: axis1, axis2 and axis3 are normalized during this operation
  3805. * @param axis1 defines the first axis
  3806. * @param axis2 defines the second axis
  3807. * @param axis3 defines the third axis
  3808. * @returns a new Vector3
  3809. */
  3810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3811. var rotation = Vector3.Zero();
  3812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3813. return rotation;
  3814. };
  3815. /**
  3816. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @param ref defines the Vector3 where to store the result
  3821. */
  3822. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3823. var quat = MathTmp.Quaternion[0];
  3824. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3825. quat.toEulerAnglesToRef(ref);
  3826. };
  3827. return Vector3;
  3828. }());
  3829. BABYLON.Vector3 = Vector3;
  3830. //Vector4 class created for EulerAngle class conversion to Quaternion
  3831. var Vector4 = /** @class */ (function () {
  3832. /**
  3833. * Creates a Vector4 object from the given floats.
  3834. */
  3835. function Vector4(x, y, z, w) {
  3836. this.x = x;
  3837. this.y = y;
  3838. this.z = z;
  3839. this.w = w;
  3840. }
  3841. /**
  3842. * Returns the string with the Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.toString = function () {
  3845. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3846. };
  3847. /**
  3848. * Returns the string "Vector4".
  3849. */
  3850. Vector4.prototype.getClassName = function () {
  3851. return "Vector4";
  3852. };
  3853. /**
  3854. * Returns the Vector4 hash code.
  3855. */
  3856. Vector4.prototype.getHashCode = function () {
  3857. var hash = this.x || 0;
  3858. hash = (hash * 397) ^ (this.y || 0);
  3859. hash = (hash * 397) ^ (this.z || 0);
  3860. hash = (hash * 397) ^ (this.w || 0);
  3861. return hash;
  3862. };
  3863. // Operators
  3864. /**
  3865. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.asArray = function () {
  3868. var result = new Array();
  3869. this.toArray(result, 0);
  3870. return result;
  3871. };
  3872. /**
  3873. * Populates the given array from the given index with the Vector4 coordinates.
  3874. * Returns the Vector4.
  3875. */
  3876. Vector4.prototype.toArray = function (array, index) {
  3877. if (index === undefined) {
  3878. index = 0;
  3879. }
  3880. array[index] = this.x;
  3881. array[index + 1] = this.y;
  3882. array[index + 2] = this.z;
  3883. array[index + 3] = this.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Adds the given vector to the current Vector4.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.addInPlace = function (otherVector) {
  3891. this.x += otherVector.x;
  3892. this.y += otherVector.y;
  3893. this.z += otherVector.z;
  3894. this.w += otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3899. */
  3900. Vector4.prototype.add = function (otherVector) {
  3901. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3902. };
  3903. /**
  3904. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3905. * Returns the current Vector4.
  3906. */
  3907. Vector4.prototype.addToRef = function (otherVector, result) {
  3908. result.x = this.x + otherVector.x;
  3909. result.y = this.y + otherVector.y;
  3910. result.z = this.z + otherVector.z;
  3911. result.w = this.w + otherVector.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Subtract in place the given vector from the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.subtractInPlace = function (otherVector) {
  3919. this.x -= otherVector.x;
  3920. this.y -= otherVector.y;
  3921. this.z -= otherVector.z;
  3922. this.w -= otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3927. */
  3928. Vector4.prototype.subtract = function (otherVector) {
  3929. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3930. };
  3931. /**
  3932. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3936. result.x = this.x - otherVector.x;
  3937. result.y = this.y - otherVector.y;
  3938. result.z = this.z - otherVector.z;
  3939. result.w = this.w - otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3946. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3947. };
  3948. /**
  3949. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3950. * Returns the current Vector4.
  3951. */
  3952. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3953. result.x = this.x - x;
  3954. result.y = this.y - y;
  3955. result.z = this.z - z;
  3956. result.w = this.w - w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3961. */
  3962. Vector4.prototype.negate = function () {
  3963. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3964. };
  3965. /**
  3966. * Multiplies the current Vector4 coordinates by scale (float).
  3967. * Returns the updated Vector4.
  3968. */
  3969. Vector4.prototype.scaleInPlace = function (scale) {
  3970. this.x *= scale;
  3971. this.y *= scale;
  3972. this.z *= scale;
  3973. this.w *= scale;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3978. */
  3979. Vector4.prototype.scale = function (scale) {
  3980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3981. };
  3982. /**
  3983. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3984. * Returns the current Vector4.
  3985. */
  3986. Vector4.prototype.scaleToRef = function (scale, result) {
  3987. result.x = this.x * scale;
  3988. result.y = this.y * scale;
  3989. result.z = this.z * scale;
  3990. result.w = this.w * scale;
  3991. return this;
  3992. };
  3993. /**
  3994. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3995. * @param scale defines the scale factor
  3996. * @param result defines the Vector4 object where to store the result
  3997. * @returns the unmodified current Vector4
  3998. */
  3999. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4000. result.x += this.x * scale;
  4001. result.y += this.y * scale;
  4002. result.z += this.z * scale;
  4003. result.w += this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4008. */
  4009. Vector4.prototype.equals = function (otherVector) {
  4010. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4011. };
  4012. /**
  4013. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4014. */
  4015. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4017. return otherVector
  4018. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4019. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4020. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4021. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4022. };
  4023. /**
  4024. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4025. */
  4026. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4027. return this.x === x && this.y === y && this.z === z && this.w === w;
  4028. };
  4029. /**
  4030. * Multiplies in place the current Vector4 by the given one.
  4031. * Returns the updated Vector4.
  4032. */
  4033. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4034. this.x *= otherVector.x;
  4035. this.y *= otherVector.y;
  4036. this.z *= otherVector.z;
  4037. this.w *= otherVector.w;
  4038. return this;
  4039. };
  4040. /**
  4041. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4042. */
  4043. Vector4.prototype.multiply = function (otherVector) {
  4044. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4045. };
  4046. /**
  4047. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4048. * Returns the current Vector4.
  4049. */
  4050. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4051. result.x = this.x * otherVector.x;
  4052. result.y = this.y * otherVector.y;
  4053. result.z = this.z * otherVector.z;
  4054. result.w = this.w * otherVector.w;
  4055. return this;
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4059. */
  4060. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4061. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4065. */
  4066. Vector4.prototype.divide = function (otherVector) {
  4067. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.divideToRef = function (otherVector, result) {
  4074. result.x = this.x / otherVector.x;
  4075. result.y = this.y / otherVector.y;
  4076. result.z = this.z / otherVector.z;
  4077. result.w = this.w / otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Divides the current Vector3 coordinates by the given ones.
  4082. * @returns the updated Vector3.
  4083. */
  4084. Vector4.prototype.divideInPlace = function (otherVector) {
  4085. return this.divideToRef(otherVector, this);
  4086. };
  4087. /**
  4088. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4089. * @param other defines the second operand
  4090. * @returns the current updated Vector4
  4091. */
  4092. Vector4.prototype.minimizeInPlace = function (other) {
  4093. if (other.x < this.x)
  4094. this.x = other.x;
  4095. if (other.y < this.y)
  4096. this.y = other.y;
  4097. if (other.z < this.z)
  4098. this.z = other.z;
  4099. if (other.w < this.w)
  4100. this.w = other.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.maximizeInPlace = function (other) {
  4109. if (other.x > this.x)
  4110. this.x = other.x;
  4111. if (other.y > this.y)
  4112. this.y = other.y;
  4113. if (other.z > this.z)
  4114. this.z = other.z;
  4115. if (other.w > this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Gets a new Vector4 from current Vector4 floored values
  4121. * @returns a new Vector4
  4122. */
  4123. Vector4.prototype.floor = function () {
  4124. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4125. };
  4126. /**
  4127. * Gets a new Vector4 from current Vector3 floored values
  4128. * @returns a new Vector4
  4129. */
  4130. Vector4.prototype.fract = function () {
  4131. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4132. };
  4133. // Properties
  4134. /**
  4135. * Returns the Vector4 length (float).
  4136. */
  4137. Vector4.prototype.length = function () {
  4138. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. /**
  4141. * Returns the Vector4 squared length (float).
  4142. */
  4143. Vector4.prototype.lengthSquared = function () {
  4144. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4145. };
  4146. // Methods
  4147. /**
  4148. * Normalizes in place the Vector4.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.normalize = function () {
  4152. var len = this.length();
  4153. if (len === 0)
  4154. return this;
  4155. var num = 1.0 / len;
  4156. this.x *= num;
  4157. this.y *= num;
  4158. this.z *= num;
  4159. this.w *= num;
  4160. return this;
  4161. };
  4162. /**
  4163. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4164. */
  4165. Vector4.prototype.toVector3 = function () {
  4166. return new Vector3(this.x, this.y, this.z);
  4167. };
  4168. /**
  4169. * Returns a new Vector4 copied from the current one.
  4170. */
  4171. Vector4.prototype.clone = function () {
  4172. return new Vector4(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Vector4 with the given one coordinates.
  4176. * Returns the updated Vector4.
  4177. */
  4178. Vector4.prototype.copyFrom = function (source) {
  4179. this.x = source.x;
  4180. this.y = source.y;
  4181. this.z = source.z;
  4182. this.w = source.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Vector4 coordinates with the given floats.
  4187. * Returns the updated Vector4.
  4188. */
  4189. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Vector4 coordinates with the given floats.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. // Statics
  4204. /**
  4205. * Returns a new Vector4 set from the starting index of the given array.
  4206. */
  4207. Vector4.FromArray = function (array, offset) {
  4208. if (!offset) {
  4209. offset = 0;
  4210. }
  4211. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4212. };
  4213. /**
  4214. * Updates the given vector "result" from the starting index of the given array.
  4215. */
  4216. Vector4.FromArrayToRef = function (array, offset, result) {
  4217. result.x = array[offset];
  4218. result.y = array[offset + 1];
  4219. result.z = array[offset + 2];
  4220. result.w = array[offset + 3];
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given Float32Array.
  4224. */
  4225. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4226. Vector4.FromArrayToRef(array, offset, result);
  4227. };
  4228. /**
  4229. * Updates the given vector "result" coordinates from the given floats.
  4230. */
  4231. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4232. result.x = x;
  4233. result.y = y;
  4234. result.z = z;
  4235. result.w = w;
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4239. */
  4240. Vector4.Zero = function () {
  4241. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4242. };
  4243. /**
  4244. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4245. */
  4246. Vector4.One = function () {
  4247. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4248. };
  4249. /**
  4250. * Returns a new normalized Vector4 from the given one.
  4251. */
  4252. Vector4.Normalize = function (vector) {
  4253. var result = Vector4.Zero();
  4254. Vector4.NormalizeToRef(vector, result);
  4255. return result;
  4256. };
  4257. /**
  4258. * Updates the given vector "result" from the normalization of the given one.
  4259. */
  4260. Vector4.NormalizeToRef = function (vector, result) {
  4261. result.copyFrom(vector);
  4262. result.normalize();
  4263. };
  4264. Vector4.Minimize = function (left, right) {
  4265. var min = left.clone();
  4266. min.minimizeInPlace(right);
  4267. return min;
  4268. };
  4269. Vector4.Maximize = function (left, right) {
  4270. var max = left.clone();
  4271. max.maximizeInPlace(right);
  4272. return max;
  4273. };
  4274. /**
  4275. * Returns the distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.Distance = function (value1, value2) {
  4278. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4279. };
  4280. /**
  4281. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4282. */
  4283. Vector4.DistanceSquared = function (value1, value2) {
  4284. var x = value1.x - value2.x;
  4285. var y = value1.y - value2.y;
  4286. var z = value1.z - value2.z;
  4287. var w = value1.w - value2.w;
  4288. return (x * x) + (y * y) + (z * z) + (w * w);
  4289. };
  4290. /**
  4291. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4292. */
  4293. Vector4.Center = function (value1, value2) {
  4294. var center = value1.add(value2);
  4295. center.scaleInPlace(0.5);
  4296. return center;
  4297. };
  4298. /**
  4299. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4300. * This methods computes transformed normalized direction vectors only.
  4301. */
  4302. Vector4.TransformNormal = function (vector, transformation) {
  4303. var result = Vector4.Zero();
  4304. Vector4.TransformNormalToRef(vector, transformation, result);
  4305. return result;
  4306. };
  4307. /**
  4308. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4312. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4313. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4314. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4315. result.x = x;
  4316. result.y = y;
  4317. result.z = z;
  4318. result.w = vector.w;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4325. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4326. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4327. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4328. result.w = w;
  4329. };
  4330. return Vector4;
  4331. }());
  4332. BABYLON.Vector4 = Vector4;
  4333. var Size = /** @class */ (function () {
  4334. /**
  4335. * Creates a Size object from the given width and height (floats).
  4336. */
  4337. function Size(width, height) {
  4338. this.width = width;
  4339. this.height = height;
  4340. }
  4341. // Returns a string with the Size width and height.
  4342. Size.prototype.toString = function () {
  4343. return "{W: " + this.width + ", H: " + this.height + "}";
  4344. };
  4345. /**
  4346. * Returns the string "Size"
  4347. */
  4348. Size.prototype.getClassName = function () {
  4349. return "Size";
  4350. };
  4351. /**
  4352. * Returns the Size hash code.
  4353. */
  4354. Size.prototype.getHashCode = function () {
  4355. var hash = this.width || 0;
  4356. hash = (hash * 397) ^ (this.height || 0);
  4357. return hash;
  4358. };
  4359. /**
  4360. * Updates the current size from the given one.
  4361. * Returns the updated Size.
  4362. */
  4363. Size.prototype.copyFrom = function (src) {
  4364. this.width = src.width;
  4365. this.height = src.height;
  4366. };
  4367. /**
  4368. * Updates in place the current Size from the given floats.
  4369. * Returns the updated Size.
  4370. */
  4371. Size.prototype.copyFromFloats = function (width, height) {
  4372. this.width = width;
  4373. this.height = height;
  4374. return this;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.set = function (width, height) {
  4381. return this.copyFromFloats(width, height);
  4382. };
  4383. /**
  4384. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4385. */
  4386. Size.prototype.multiplyByFloats = function (w, h) {
  4387. return new Size(this.width * w, this.height * h);
  4388. };
  4389. /**
  4390. * Returns a new Size copied from the given one.
  4391. */
  4392. Size.prototype.clone = function () {
  4393. return new Size(this.width, this.height);
  4394. };
  4395. /**
  4396. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4397. */
  4398. Size.prototype.equals = function (other) {
  4399. if (!other) {
  4400. return false;
  4401. }
  4402. return (this.width === other.width) && (this.height === other.height);
  4403. };
  4404. Object.defineProperty(Size.prototype, "surface", {
  4405. /**
  4406. * Returns the surface of the Size : width * height (float).
  4407. */
  4408. get: function () {
  4409. return this.width * this.height;
  4410. },
  4411. enumerable: true,
  4412. configurable: true
  4413. });
  4414. /**
  4415. * Returns a new Size set to (0.0, 0.0)
  4416. */
  4417. Size.Zero = function () {
  4418. return new Size(0.0, 0.0);
  4419. };
  4420. /**
  4421. * Returns a new Size set as the addition result of the current Size and the given one.
  4422. */
  4423. Size.prototype.add = function (otherSize) {
  4424. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4425. return r;
  4426. };
  4427. /**
  4428. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4429. */
  4430. Size.prototype.subtract = function (otherSize) {
  4431. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4432. return r;
  4433. };
  4434. /**
  4435. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4436. */
  4437. Size.Lerp = function (start, end, amount) {
  4438. var w = start.width + ((end.width - start.width) * amount);
  4439. var h = start.height + ((end.height - start.height) * amount);
  4440. return new Size(w, h);
  4441. };
  4442. return Size;
  4443. }());
  4444. BABYLON.Size = Size;
  4445. /**
  4446. * Class used to store quaternion data
  4447. * @see https://en.wikipedia.org/wiki/Quaternion
  4448. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4449. */
  4450. var Quaternion = /** @class */ (function () {
  4451. /**
  4452. * Creates a new Quaternion from the given floats
  4453. * @param x defines the first component (0 by default)
  4454. * @param y defines the second component (0 by default)
  4455. * @param z defines the third component (0 by default)
  4456. * @param w defines the fourth component (1.0 by default)
  4457. */
  4458. function Quaternion(
  4459. /** defines the first component (0 by default) */
  4460. x,
  4461. /** defines the second component (0 by default) */
  4462. y,
  4463. /** defines the third component (0 by default) */
  4464. z,
  4465. /** defines the fourth component (1.0 by default) */
  4466. w) {
  4467. if (x === void 0) { x = 0.0; }
  4468. if (y === void 0) { y = 0.0; }
  4469. if (z === void 0) { z = 0.0; }
  4470. if (w === void 0) { w = 1.0; }
  4471. this.x = x;
  4472. this.y = y;
  4473. this.z = z;
  4474. this.w = w;
  4475. }
  4476. /**
  4477. * Gets a string representation for the current quaternion
  4478. * @returns a string with the Quaternion coordinates
  4479. */
  4480. Quaternion.prototype.toString = function () {
  4481. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4482. };
  4483. /**
  4484. * Gets the class name of the quaternion
  4485. * @returns the string "Quaternion"
  4486. */
  4487. Quaternion.prototype.getClassName = function () {
  4488. return "Quaternion";
  4489. };
  4490. /**
  4491. * Gets a hash code for this quaternion
  4492. * @returns the quaternion hash code
  4493. */
  4494. Quaternion.prototype.getHashCode = function () {
  4495. var hash = this.x || 0;
  4496. hash = (hash * 397) ^ (this.y || 0);
  4497. hash = (hash * 397) ^ (this.z || 0);
  4498. hash = (hash * 397) ^ (this.w || 0);
  4499. return hash;
  4500. };
  4501. /**
  4502. * Copy the quaternion to an array
  4503. * @returns a new array populated with 4 elements from the quaternion coordinates
  4504. */
  4505. Quaternion.prototype.asArray = function () {
  4506. return [this.x, this.y, this.z, this.w];
  4507. };
  4508. /**
  4509. * Check if two quaternions are equals
  4510. * @param otherQuaternion defines the second operand
  4511. * @return true if the current quaternion and the given one coordinates are strictly equals
  4512. */
  4513. Quaternion.prototype.equals = function (otherQuaternion) {
  4514. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4515. };
  4516. /**
  4517. * Clone the current quaternion
  4518. * @returns a new quaternion copied from the current one
  4519. */
  4520. Quaternion.prototype.clone = function () {
  4521. return new Quaternion(this.x, this.y, this.z, this.w);
  4522. };
  4523. /**
  4524. * Copy a quaternion to the current one
  4525. * @param other defines the other quaternion
  4526. * @returns the updated current quaternion
  4527. */
  4528. Quaternion.prototype.copyFrom = function (other) {
  4529. this.x = other.x;
  4530. this.y = other.y;
  4531. this.z = other.z;
  4532. this.w = other.w;
  4533. return this;
  4534. };
  4535. /**
  4536. * Updates the current quaternion with the given float coordinates
  4537. * @param x defines the x coordinate
  4538. * @param y defines the y coordinate
  4539. * @param z defines the z coordinate
  4540. * @param w defines the w coordinate
  4541. * @returns the updated current quaternion
  4542. */
  4543. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4544. this.x = x;
  4545. this.y = y;
  4546. this.z = z;
  4547. this.w = w;
  4548. return this;
  4549. };
  4550. /**
  4551. * Updates the current quaternion from the given float coordinates
  4552. * @param x defines the x coordinate
  4553. * @param y defines the y coordinate
  4554. * @param z defines the z coordinate
  4555. * @param w defines the w coordinate
  4556. * @returns the updated current quaternion
  4557. */
  4558. Quaternion.prototype.set = function (x, y, z, w) {
  4559. return this.copyFromFloats(x, y, z, w);
  4560. };
  4561. /**
  4562. * Adds two quaternions
  4563. * @param other defines the second operand
  4564. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4565. */
  4566. Quaternion.prototype.add = function (other) {
  4567. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4568. };
  4569. /**
  4570. * Add a quaternion to the current one
  4571. * @param other defines the quaternion to add
  4572. * @returns the current quaternion
  4573. */
  4574. Quaternion.prototype.addInPlace = function (other) {
  4575. this.x += other.x;
  4576. this.y += other.y;
  4577. this.z += other.z;
  4578. this.w += other.w;
  4579. return this;
  4580. };
  4581. /**
  4582. * Subtract two quaternions
  4583. * @param other defines the second operand
  4584. * @returns a new quaternion as the subtraction result of the given one from the current one
  4585. */
  4586. Quaternion.prototype.subtract = function (other) {
  4587. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4588. };
  4589. /**
  4590. * Multiplies the current quaternion by a scale factor
  4591. * @param value defines the scale factor
  4592. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4593. */
  4594. Quaternion.prototype.scale = function (value) {
  4595. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4596. };
  4597. /**
  4598. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4599. * @param scale defines the scale factor
  4600. * @param result defines the Quaternion object where to store the result
  4601. * @returns the unmodified current quaternion
  4602. */
  4603. Quaternion.prototype.scaleToRef = function (scale, result) {
  4604. result.x = this.x * scale;
  4605. result.y = this.y * scale;
  4606. result.z = this.z * scale;
  4607. result.w = this.w * scale;
  4608. return this;
  4609. };
  4610. /**
  4611. * Multiplies in place the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns the current modified quaternion
  4614. */
  4615. Quaternion.prototype.scaleInPlace = function (value) {
  4616. this.x *= value;
  4617. this.y *= value;
  4618. this.z *= value;
  4619. this.w *= value;
  4620. return this;
  4621. };
  4622. /**
  4623. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4624. * @param scale defines the scale factor
  4625. * @param result defines the Quaternion object where to store the result
  4626. * @returns the unmodified current quaternion
  4627. */
  4628. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4629. result.x += this.x * scale;
  4630. result.y += this.y * scale;
  4631. result.z += this.z * scale;
  4632. result.w += this.w * scale;
  4633. return this;
  4634. };
  4635. /**
  4636. * Multiplies two quaternions
  4637. * @param q1 defines the second operand
  4638. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4639. */
  4640. Quaternion.prototype.multiply = function (q1) {
  4641. var result = new Quaternion(0, 0, 0, 1.0);
  4642. this.multiplyToRef(q1, result);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4647. * @param q1 defines the second operand
  4648. * @param result defines the target quaternion
  4649. * @returns the current quaternion
  4650. */
  4651. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4652. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4653. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4654. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4655. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4656. result.copyFromFloats(x, y, z, w);
  4657. return this;
  4658. };
  4659. /**
  4660. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @returns the currentupdated quaternion
  4663. */
  4664. Quaternion.prototype.multiplyInPlace = function (q1) {
  4665. this.multiplyToRef(q1, this);
  4666. return this;
  4667. };
  4668. /**
  4669. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4670. * @param ref defines the target quaternion
  4671. * @returns the current quaternion
  4672. */
  4673. Quaternion.prototype.conjugateToRef = function (ref) {
  4674. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates in place (1-q) the current quaternion
  4679. * @returns the current updated quaternion
  4680. */
  4681. Quaternion.prototype.conjugateInPlace = function () {
  4682. this.x *= -1;
  4683. this.y *= -1;
  4684. this.z *= -1;
  4685. return this;
  4686. };
  4687. /**
  4688. * Conjugates in place (1-q) the current quaternion
  4689. * @returns a new quaternion
  4690. */
  4691. Quaternion.prototype.conjugate = function () {
  4692. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4693. return result;
  4694. };
  4695. /**
  4696. * Gets length of current quaternion
  4697. * @returns the quaternion length (float)
  4698. */
  4699. Quaternion.prototype.length = function () {
  4700. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4701. };
  4702. /**
  4703. * Normalize in place the current quaternion
  4704. * @returns the current updated quaternion
  4705. */
  4706. Quaternion.prototype.normalize = function () {
  4707. var length = 1.0 / this.length();
  4708. this.x *= length;
  4709. this.y *= length;
  4710. this.z *= length;
  4711. this.w *= length;
  4712. return this;
  4713. };
  4714. /**
  4715. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4716. * @param order is a reserved parameter and is ignore for now
  4717. * @returns a new Vector3 containing the Euler angles
  4718. */
  4719. Quaternion.prototype.toEulerAngles = function (order) {
  4720. if (order === void 0) { order = "YZX"; }
  4721. var result = Vector3.Zero();
  4722. this.toEulerAnglesToRef(result, order);
  4723. return result;
  4724. };
  4725. /**
  4726. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4727. * @param result defines the vector which will be filled with the Euler angles
  4728. * @param order is a reserved parameter and is ignore for now
  4729. * @returns the current unchanged quaternion
  4730. */
  4731. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4732. if (order === void 0) { order = "YZX"; }
  4733. var qz = this.z;
  4734. var qx = this.x;
  4735. var qy = this.y;
  4736. var qw = this.w;
  4737. var sqw = qw * qw;
  4738. var sqz = qz * qz;
  4739. var sqx = qx * qx;
  4740. var sqy = qy * qy;
  4741. var zAxisY = qy * qz - qx * qw;
  4742. var limit = .4999999;
  4743. if (zAxisY < -limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else if (zAxisY > limit) {
  4749. result.y = 2 * Math.atan2(qy, qw);
  4750. result.x = -Math.PI / 2;
  4751. result.z = 0;
  4752. }
  4753. else {
  4754. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4755. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4756. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4757. }
  4758. return this;
  4759. };
  4760. /**
  4761. * Updates the given rotation matrix with the current quaternion values
  4762. * @param result defines the target matrix
  4763. * @returns the current unchanged quaternion
  4764. */
  4765. Quaternion.prototype.toRotationMatrix = function (result) {
  4766. var xx = this.x * this.x;
  4767. var yy = this.y * this.y;
  4768. var zz = this.z * this.z;
  4769. var xy = this.x * this.y;
  4770. var zw = this.z * this.w;
  4771. var zx = this.z * this.x;
  4772. var yw = this.y * this.w;
  4773. var yz = this.y * this.z;
  4774. var xw = this.x * this.w;
  4775. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4776. result.m[1] = 2.0 * (xy + zw);
  4777. result.m[2] = 2.0 * (zx - yw);
  4778. result.m[3] = 0;
  4779. result.m[4] = 2.0 * (xy - zw);
  4780. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4781. result.m[6] = 2.0 * (yz + xw);
  4782. result.m[7] = 0;
  4783. result.m[8] = 2.0 * (zx + yw);
  4784. result.m[9] = 2.0 * (yz - xw);
  4785. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4786. result.m[11] = 0;
  4787. result.m[12] = 0;
  4788. result.m[13] = 0;
  4789. result.m[14] = 0;
  4790. result.m[15] = 1.0;
  4791. result._markAsUpdated();
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion from the given rotation matrix values
  4796. * @param matrix defines the source matrix
  4797. * @returns the current updated quaternion
  4798. */
  4799. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4800. Quaternion.FromRotationMatrixToRef(matrix, this);
  4801. return this;
  4802. };
  4803. // Statics
  4804. /**
  4805. * Creates a new quaternion from a rotation matrix
  4806. * @param matrix defines the source matrix
  4807. * @returns a new quaternion created from the given rotation matrix values
  4808. */
  4809. Quaternion.FromRotationMatrix = function (matrix) {
  4810. var result = new Quaternion();
  4811. Quaternion.FromRotationMatrixToRef(matrix, result);
  4812. return result;
  4813. };
  4814. /**
  4815. * Updates the given quaternion with the given rotation matrix values
  4816. * @param matrix defines the source matrix
  4817. * @param result defines the target quaternion
  4818. */
  4819. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4820. var data = matrix.m;
  4821. var m11 = data[0], m12 = data[4], m13 = data[8];
  4822. var m21 = data[1], m22 = data[5], m23 = data[9];
  4823. var m31 = data[2], m32 = data[6], m33 = data[10];
  4824. var trace = m11 + m22 + m33;
  4825. var s;
  4826. if (trace > 0) {
  4827. s = 0.5 / Math.sqrt(trace + 1.0);
  4828. result.w = 0.25 / s;
  4829. result.x = (m32 - m23) * s;
  4830. result.y = (m13 - m31) * s;
  4831. result.z = (m21 - m12) * s;
  4832. }
  4833. else if (m11 > m22 && m11 > m33) {
  4834. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4835. result.w = (m32 - m23) / s;
  4836. result.x = 0.25 * s;
  4837. result.y = (m12 + m21) / s;
  4838. result.z = (m13 + m31) / s;
  4839. }
  4840. else if (m22 > m33) {
  4841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4842. result.w = (m13 - m31) / s;
  4843. result.x = (m12 + m21) / s;
  4844. result.y = 0.25 * s;
  4845. result.z = (m23 + m32) / s;
  4846. }
  4847. else {
  4848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4849. result.w = (m21 - m12) / s;
  4850. result.x = (m13 + m31) / s;
  4851. result.y = (m23 + m32) / s;
  4852. result.z = 0.25 * s;
  4853. }
  4854. };
  4855. /**
  4856. * Returns the dot product (float) between the quaternions "left" and "right"
  4857. * @param left defines the left operand
  4858. * @param right defines the right operand
  4859. * @returns the dot product
  4860. */
  4861. Quaternion.Dot = function (left, right) {
  4862. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4863. };
  4864. /**
  4865. * Checks if the two quaternions are close to each other
  4866. * @param quat0 defines the first quaternion to check
  4867. * @param quat1 defines the second quaternion to check
  4868. * @returns true if the two quaternions are close to each other
  4869. */
  4870. Quaternion.AreClose = function (quat0, quat1) {
  4871. var dot = Quaternion.Dot(quat0, quat1);
  4872. return dot >= 0;
  4873. };
  4874. /**
  4875. * Creates an empty quaternion
  4876. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4877. */
  4878. Quaternion.Zero = function () {
  4879. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4880. };
  4881. /**
  4882. * Inverse a given quaternion
  4883. * @param q defines the source quaternion
  4884. * @returns a new quaternion as the inverted current quaternion
  4885. */
  4886. Quaternion.Inverse = function (q) {
  4887. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4888. };
  4889. /**
  4890. * Creates an identity quaternion
  4891. * @returns the identity quaternion
  4892. */
  4893. Quaternion.Identity = function () {
  4894. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4895. };
  4896. /**
  4897. * Gets a boolean indicating if the given quaternion is identity
  4898. * @param quaternion defines the quaternion to check
  4899. * @returns true if the quaternion is identity
  4900. */
  4901. Quaternion.IsIdentity = function (quaternion) {
  4902. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4903. };
  4904. /**
  4905. * Creates a quaternion from a rotation around an axis
  4906. * @param axis defines the axis to use
  4907. * @param angle defines the angle to use
  4908. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4909. */
  4910. Quaternion.RotationAxis = function (axis, angle) {
  4911. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4912. };
  4913. /**
  4914. * Creates a rotation around an axis and stores it into the given quaternion
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @param result defines the target quaternion
  4918. * @returns the target quaternion
  4919. */
  4920. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4921. var sin = Math.sin(angle / 2);
  4922. axis.normalize();
  4923. result.w = Math.cos(angle / 2);
  4924. result.x = axis.x * sin;
  4925. result.y = axis.y * sin;
  4926. result.z = axis.z * sin;
  4927. return result;
  4928. };
  4929. /**
  4930. * Creates a new quaternion from data stored into an array
  4931. * @param array defines the data source
  4932. * @param offset defines the offset in the source array where the data starts
  4933. * @returns a new quaternion
  4934. */
  4935. Quaternion.FromArray = function (array, offset) {
  4936. if (!offset) {
  4937. offset = 0;
  4938. }
  4939. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4940. };
  4941. /**
  4942. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4943. * @param yaw defines the rotation around Y axis
  4944. * @param pitch defines the rotation around X axis
  4945. * @param roll defines the rotation around Z axis
  4946. * @returns the new quaternion
  4947. */
  4948. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4949. var q = new Quaternion();
  4950. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4951. return q;
  4952. };
  4953. /**
  4954. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4955. * @param yaw defines the rotation around Y axis
  4956. * @param pitch defines the rotation around X axis
  4957. * @param roll defines the rotation around Z axis
  4958. * @param result defines the target quaternion
  4959. */
  4960. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4961. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4962. var halfRoll = roll * 0.5;
  4963. var halfPitch = pitch * 0.5;
  4964. var halfYaw = yaw * 0.5;
  4965. var sinRoll = Math.sin(halfRoll);
  4966. var cosRoll = Math.cos(halfRoll);
  4967. var sinPitch = Math.sin(halfPitch);
  4968. var cosPitch = Math.cos(halfPitch);
  4969. var sinYaw = Math.sin(halfYaw);
  4970. var cosYaw = Math.cos(halfYaw);
  4971. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4972. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4973. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4974. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4975. };
  4976. /**
  4977. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4978. * @param alpha defines the rotation around first axis
  4979. * @param beta defines the rotation around second axis
  4980. * @param gamma defines the rotation around third axis
  4981. * @returns the new quaternion
  4982. */
  4983. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4984. var result = new Quaternion();
  4985. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4986. return result;
  4987. };
  4988. /**
  4989. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4990. * @param alpha defines the rotation around first axis
  4991. * @param beta defines the rotation around second axis
  4992. * @param gamma defines the rotation around third axis
  4993. * @param result defines the target quaternion
  4994. */
  4995. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4996. // Produces a quaternion from Euler angles in the z-x-z orientation
  4997. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4998. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4999. var halfBeta = beta * 0.5;
  5000. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5001. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5002. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5003. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5004. };
  5005. /**
  5006. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5007. * @param axis1 defines the first axis
  5008. * @param axis2 defines the second axis
  5009. * @param axis3 defines the third axis
  5010. * @returns the new quaternion
  5011. */
  5012. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5013. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5014. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5015. return quat;
  5016. };
  5017. /**
  5018. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5019. * @param axis1 defines the first axis
  5020. * @param axis2 defines the second axis
  5021. * @param axis3 defines the third axis
  5022. * @param ref defines the target quaternion
  5023. */
  5024. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5025. var rotMat = MathTmp.Matrix[0];
  5026. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5027. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5028. };
  5029. /**
  5030. * Interpolates between two quaternions
  5031. * @param left defines first quaternion
  5032. * @param right defines second quaternion
  5033. * @param amount defines the gradient to use
  5034. * @returns the new interpolated quaternion
  5035. */
  5036. Quaternion.Slerp = function (left, right, amount) {
  5037. var result = Quaternion.Identity();
  5038. Quaternion.SlerpToRef(left, right, amount, result);
  5039. return result;
  5040. };
  5041. /**
  5042. * Interpolates between two quaternions and stores it into a target quaternion
  5043. * @param left defines first quaternion
  5044. * @param right defines second quaternion
  5045. * @param amount defines the gradient to use
  5046. * @param result defines the target quaternion
  5047. */
  5048. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5049. var num2;
  5050. var num3;
  5051. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5052. var flag = false;
  5053. if (num4 < 0) {
  5054. flag = true;
  5055. num4 = -num4;
  5056. }
  5057. if (num4 > 0.999999) {
  5058. num3 = 1 - amount;
  5059. num2 = flag ? -amount : amount;
  5060. }
  5061. else {
  5062. var num5 = Math.acos(num4);
  5063. var num6 = (1.0 / Math.sin(num5));
  5064. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5065. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5066. }
  5067. result.x = (num3 * left.x) + (num2 * right.x);
  5068. result.y = (num3 * left.y) + (num2 * right.y);
  5069. result.z = (num3 * left.z) + (num2 * right.z);
  5070. result.w = (num3 * left.w) + (num2 * right.w);
  5071. };
  5072. /**
  5073. * Interpolate between two quaternions using Hermite interpolation
  5074. * @param value1 defines first quaternion
  5075. * @param tangent1 defines the incoming tangent
  5076. * @param value2 defines second quaternion
  5077. * @param tangent2 defines the outgoing tangent
  5078. * @param amount defines the target quaternion
  5079. * @returns the new interpolated quaternion
  5080. */
  5081. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5082. var squared = amount * amount;
  5083. var cubed = amount * squared;
  5084. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5085. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5086. var part3 = (cubed - (2.0 * squared)) + amount;
  5087. var part4 = cubed - squared;
  5088. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5089. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5090. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5091. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5092. return new Quaternion(x, y, z, w);
  5093. };
  5094. return Quaternion;
  5095. }());
  5096. BABYLON.Quaternion = Quaternion;
  5097. /**
  5098. * Class used to store matrix data (4x4)
  5099. */
  5100. var Matrix = /** @class */ (function () {
  5101. /**
  5102. * Creates an empty matrix (filled with zeros)
  5103. */
  5104. function Matrix() {
  5105. this._isIdentity = false;
  5106. this._isIdentityDirty = true;
  5107. /**
  5108. * Gets or sets the internal data of the matrix
  5109. */
  5110. this.m = new Float32Array(16);
  5111. this._markAsUpdated();
  5112. }
  5113. /** @hidden */
  5114. Matrix.prototype._markAsUpdated = function () {
  5115. this.updateFlag = Matrix._updateFlagSeed++;
  5116. this._isIdentityDirty = true;
  5117. };
  5118. // Properties
  5119. /**
  5120. * Check if the current matrix is indentity
  5121. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5122. * @returns true is the matrix is the identity matrix
  5123. */
  5124. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5125. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5126. if (this._isIdentityDirty) {
  5127. this._isIdentityDirty = false;
  5128. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5132. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5133. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5134. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. else {
  5138. this._isIdentity = true;
  5139. }
  5140. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5141. this._isIdentity = false;
  5142. }
  5143. }
  5144. return this._isIdentity;
  5145. };
  5146. /**
  5147. * Gets the determinant of the matrix
  5148. * @returns the matrix determinant
  5149. */
  5150. Matrix.prototype.determinant = function () {
  5151. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5152. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5153. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5154. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5155. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5156. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5157. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5158. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5159. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5160. };
  5161. // Methods
  5162. /**
  5163. * Returns the matrix as a Float32Array
  5164. * @returns the matrix underlying array
  5165. */
  5166. Matrix.prototype.toArray = function () {
  5167. return this.m;
  5168. };
  5169. /**
  5170. * Returns the matrix as a Float32Array
  5171. * @returns the matrix underlying array.
  5172. */
  5173. Matrix.prototype.asArray = function () {
  5174. return this.toArray();
  5175. };
  5176. /**
  5177. * Inverts the current matrix in place
  5178. * @returns the current inverted matrix
  5179. */
  5180. Matrix.prototype.invert = function () {
  5181. this.invertToRef(this);
  5182. return this;
  5183. };
  5184. /**
  5185. * Sets all the matrix elements to zero
  5186. * @returns the current matrix
  5187. */
  5188. Matrix.prototype.reset = function () {
  5189. for (var index = 0; index < 16; index++) {
  5190. this.m[index] = 0.0;
  5191. }
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Adds the current matrix with a second one
  5197. * @param other defines the matrix to add
  5198. * @returns a new matrix as the addition of the current matrix and the given one
  5199. */
  5200. Matrix.prototype.add = function (other) {
  5201. var result = new Matrix();
  5202. this.addToRef(other, result);
  5203. return result;
  5204. };
  5205. /**
  5206. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5207. * @param other defines the matrix to add
  5208. * @param result defines the target matrix
  5209. * @returns the current matrix
  5210. */
  5211. Matrix.prototype.addToRef = function (other, result) {
  5212. for (var index = 0; index < 16; index++) {
  5213. result.m[index] = this.m[index] + other.m[index];
  5214. }
  5215. result._markAsUpdated();
  5216. return this;
  5217. };
  5218. /**
  5219. * Adds in place the given matrix to the current matrix
  5220. * @param other defines the second operand
  5221. * @returns the current updated matrix
  5222. */
  5223. Matrix.prototype.addToSelf = function (other) {
  5224. for (var index = 0; index < 16; index++) {
  5225. this.m[index] += other.m[index];
  5226. }
  5227. this._markAsUpdated();
  5228. return this;
  5229. };
  5230. /**
  5231. * Sets the given matrix to the current inverted Matrix
  5232. * @param other defines the target matrix
  5233. * @returns the unmodified current matrix
  5234. */
  5235. Matrix.prototype.invertToRef = function (other) {
  5236. var l1 = this.m[0];
  5237. var l2 = this.m[1];
  5238. var l3 = this.m[2];
  5239. var l4 = this.m[3];
  5240. var l5 = this.m[4];
  5241. var l6 = this.m[5];
  5242. var l7 = this.m[6];
  5243. var l8 = this.m[7];
  5244. var l9 = this.m[8];
  5245. var l10 = this.m[9];
  5246. var l11 = this.m[10];
  5247. var l12 = this.m[11];
  5248. var l13 = this.m[12];
  5249. var l14 = this.m[13];
  5250. var l15 = this.m[14];
  5251. var l16 = this.m[15];
  5252. var l17 = (l11 * l16) - (l12 * l15);
  5253. var l18 = (l10 * l16) - (l12 * l14);
  5254. var l19 = (l10 * l15) - (l11 * l14);
  5255. var l20 = (l9 * l16) - (l12 * l13);
  5256. var l21 = (l9 * l15) - (l11 * l13);
  5257. var l22 = (l9 * l14) - (l10 * l13);
  5258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5263. var l28 = (l7 * l16) - (l8 * l15);
  5264. var l29 = (l6 * l16) - (l8 * l14);
  5265. var l30 = (l6 * l15) - (l7 * l14);
  5266. var l31 = (l5 * l16) - (l8 * l13);
  5267. var l32 = (l5 * l15) - (l7 * l13);
  5268. var l33 = (l5 * l14) - (l6 * l13);
  5269. var l34 = (l7 * l12) - (l8 * l11);
  5270. var l35 = (l6 * l12) - (l8 * l10);
  5271. var l36 = (l6 * l11) - (l7 * l10);
  5272. var l37 = (l5 * l12) - (l8 * l9);
  5273. var l38 = (l5 * l11) - (l7 * l9);
  5274. var l39 = (l5 * l10) - (l6 * l9);
  5275. other.m[0] = l23 * l27;
  5276. other.m[4] = l24 * l27;
  5277. other.m[8] = l25 * l27;
  5278. other.m[12] = l26 * l27;
  5279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5291. other._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Inserts the translation vector (using 3 floats) in the current matrix
  5296. * @param x defines the 1st component of the translation
  5297. * @param y defines the 2nd component of the translation
  5298. * @param z defines the 3rd component of the translation
  5299. * @returns the current updated matrix
  5300. */
  5301. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5302. this.m[12] = x;
  5303. this.m[13] = y;
  5304. this.m[14] = z;
  5305. this._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector in the current matrix
  5310. * @param vector3 defines the translation to insert
  5311. * @returns the current updated matrix
  5312. */
  5313. Matrix.prototype.setTranslation = function (vector3) {
  5314. this.m[12] = vector3.x;
  5315. this.m[13] = vector3.y;
  5316. this.m[14] = vector3.z;
  5317. this._markAsUpdated();
  5318. return this;
  5319. };
  5320. /**
  5321. * Gets the translation value of the current matrix
  5322. * @returns a new Vector3 as the extracted translation from the matrix
  5323. */
  5324. Matrix.prototype.getTranslation = function () {
  5325. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5326. };
  5327. /**
  5328. * Fill a Vector3 with the extracted translation from the matrix
  5329. * @param result defines the Vector3 where to store the translation
  5330. * @returns the current matrix
  5331. */
  5332. Matrix.prototype.getTranslationToRef = function (result) {
  5333. result.x = this.m[12];
  5334. result.y = this.m[13];
  5335. result.z = this.m[14];
  5336. return this;
  5337. };
  5338. /**
  5339. * Remove rotation and scaling part from the matrix
  5340. * @returns the updated matrix
  5341. */
  5342. Matrix.prototype.removeRotationAndScaling = function () {
  5343. this.setRowFromFloats(0, 1, 0, 0, 0);
  5344. this.setRowFromFloats(1, 0, 1, 0, 0);
  5345. this.setRowFromFloats(2, 0, 0, 1, 0);
  5346. return this;
  5347. };
  5348. /**
  5349. * Multiply two matrices
  5350. * @param other defines the second operand
  5351. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5352. */
  5353. Matrix.prototype.multiply = function (other) {
  5354. var result = new Matrix();
  5355. this.multiplyToRef(other, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Copy the current matrix from the given one
  5360. * @param other defines the source matrix
  5361. * @returns the current updated matrix
  5362. */
  5363. Matrix.prototype.copyFrom = function (other) {
  5364. for (var index = 0; index < 16; index++) {
  5365. this.m[index] = other.m[index];
  5366. }
  5367. this._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Populates the given array from the starting index with the current matrix values
  5372. * @param array defines the target array
  5373. * @param offset defines the offset in the target array where to start storing values
  5374. * @returns the current matrix
  5375. */
  5376. Matrix.prototype.copyToArray = function (array, offset) {
  5377. if (offset === void 0) { offset = 0; }
  5378. for (var index = 0; index < 16; index++) {
  5379. array[offset + index] = this.m[index];
  5380. }
  5381. return this;
  5382. };
  5383. /**
  5384. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5385. * @param other defines the second operand
  5386. * @param result defines the matrix where to store the multiplication
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.multiplyToRef = function (other, result) {
  5390. this.multiplyToArray(other, result.m, 0);
  5391. result._markAsUpdated();
  5392. return this;
  5393. };
  5394. /**
  5395. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5396. * @param other defines the second operand
  5397. * @param result defines the array where to store the multiplication
  5398. * @param offset defines the offset in the target array where to start storing values
  5399. * @returns the current matrix
  5400. */
  5401. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5402. var tm0 = this.m[0];
  5403. var tm1 = this.m[1];
  5404. var tm2 = this.m[2];
  5405. var tm3 = this.m[3];
  5406. var tm4 = this.m[4];
  5407. var tm5 = this.m[5];
  5408. var tm6 = this.m[6];
  5409. var tm7 = this.m[7];
  5410. var tm8 = this.m[8];
  5411. var tm9 = this.m[9];
  5412. var tm10 = this.m[10];
  5413. var tm11 = this.m[11];
  5414. var tm12 = this.m[12];
  5415. var tm13 = this.m[13];
  5416. var tm14 = this.m[14];
  5417. var tm15 = this.m[15];
  5418. var om0 = other.m[0];
  5419. var om1 = other.m[1];
  5420. var om2 = other.m[2];
  5421. var om3 = other.m[3];
  5422. var om4 = other.m[4];
  5423. var om5 = other.m[5];
  5424. var om6 = other.m[6];
  5425. var om7 = other.m[7];
  5426. var om8 = other.m[8];
  5427. var om9 = other.m[9];
  5428. var om10 = other.m[10];
  5429. var om11 = other.m[11];
  5430. var om12 = other.m[12];
  5431. var om13 = other.m[13];
  5432. var om14 = other.m[14];
  5433. var om15 = other.m[15];
  5434. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5435. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5436. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5437. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5438. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5439. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5440. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5441. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5442. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5443. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5444. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5445. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5446. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5447. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5448. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5449. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5450. return this;
  5451. };
  5452. /**
  5453. * Check equality between this matrix and a second one
  5454. * @param value defines the second matrix to compare
  5455. * @returns true is the current matrix and the given one values are strictly equal
  5456. */
  5457. Matrix.prototype.equals = function (value) {
  5458. return value &&
  5459. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5460. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5461. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5462. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5463. };
  5464. /**
  5465. * Clone the current matrix
  5466. * @returns a new matrix from the current matrix
  5467. */
  5468. Matrix.prototype.clone = function () {
  5469. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5470. };
  5471. /**
  5472. * Returns the name of the current matrix class
  5473. * @returns the string "Matrix"
  5474. */
  5475. Matrix.prototype.getClassName = function () {
  5476. return "Matrix";
  5477. };
  5478. /**
  5479. * Gets the hash code of the current matrix
  5480. * @returns the hash code
  5481. */
  5482. Matrix.prototype.getHashCode = function () {
  5483. var hash = this.m[0] || 0;
  5484. for (var i = 1; i < 16; i++) {
  5485. hash = (hash * 397) ^ (this.m[i] || 0);
  5486. }
  5487. return hash;
  5488. };
  5489. /**
  5490. * Decomposes the current Matrix into a translation, rotation and scaling components
  5491. * @param scale defines the scale vector3 given as a reference to update
  5492. * @param rotation defines the rotation quaternion given as a reference to update
  5493. * @param translation defines the translation vector3 given as a reference to update
  5494. * @returns true if operation was successful
  5495. */
  5496. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5497. if (translation) {
  5498. translation.x = this.m[12];
  5499. translation.y = this.m[13];
  5500. translation.z = this.m[14];
  5501. }
  5502. scale = scale || MathTmp.Vector3[0];
  5503. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5504. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5505. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5506. if (this.determinant() <= 0) {
  5507. scale.y *= -1;
  5508. }
  5509. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5510. if (rotation) {
  5511. rotation.x = 0;
  5512. rotation.y = 0;
  5513. rotation.z = 0;
  5514. rotation.w = 1;
  5515. }
  5516. return false;
  5517. }
  5518. if (rotation) {
  5519. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5520. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5521. }
  5522. return true;
  5523. };
  5524. /**
  5525. * Gets specific row of the matrix
  5526. * @param index defines the number of the row to get
  5527. * @returns the index-th row of the current matrix as a new Vector4
  5528. */
  5529. Matrix.prototype.getRow = function (index) {
  5530. if (index < 0 || index > 3) {
  5531. return null;
  5532. }
  5533. var i = index * 4;
  5534. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5535. };
  5536. /**
  5537. * Sets the index-th row of the current matrix to the vector4 values
  5538. * @param index defines the number of the row to set
  5539. * @param row defines the target vector4
  5540. * @returns the updated current matrix
  5541. */
  5542. Matrix.prototype.setRow = function (index, row) {
  5543. if (index < 0 || index > 3) {
  5544. return this;
  5545. }
  5546. var i = index * 4;
  5547. this.m[i + 0] = row.x;
  5548. this.m[i + 1] = row.y;
  5549. this.m[i + 2] = row.z;
  5550. this.m[i + 3] = row.w;
  5551. this._markAsUpdated();
  5552. return this;
  5553. };
  5554. /**
  5555. * Compute the transpose of the matrix
  5556. * @returns the new transposed matrix
  5557. */
  5558. Matrix.prototype.transpose = function () {
  5559. return Matrix.Transpose(this);
  5560. };
  5561. /**
  5562. * Compute the transpose of the matrix and store it in a given matrix
  5563. * @param result defines the target matrix
  5564. * @returns the current matrix
  5565. */
  5566. Matrix.prototype.transposeToRef = function (result) {
  5567. Matrix.TransposeToRef(this, result);
  5568. return this;
  5569. };
  5570. /**
  5571. * Sets the index-th row of the current matrix with the given 4 x float values
  5572. * @param index defines the row index
  5573. * @param x defines the x component to set
  5574. * @param y defines the y component to set
  5575. * @param z defines the z component to set
  5576. * @param w defines the w component to set
  5577. * @returns the updated current matrix
  5578. */
  5579. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5580. if (index < 0 || index > 3) {
  5581. return this;
  5582. }
  5583. var i = index * 4;
  5584. this.m[i + 0] = x;
  5585. this.m[i + 1] = y;
  5586. this.m[i + 2] = z;
  5587. this.m[i + 3] = w;
  5588. this._markAsUpdated();
  5589. return this;
  5590. };
  5591. /**
  5592. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5593. * @param scale defines the scale factor
  5594. * @returns a new matrix
  5595. */
  5596. Matrix.prototype.scale = function (scale) {
  5597. var result = new Matrix();
  5598. this.scaleToRef(scale, result);
  5599. return result;
  5600. };
  5601. /**
  5602. * Scale the current matrix values by a factor to a given result matrix
  5603. * @param scale defines the scale factor
  5604. * @param result defines the matrix to store the result
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.scaleToRef = function (scale, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] = this.m[index] * scale;
  5610. }
  5611. result._markAsUpdated();
  5612. return this;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor and add the result to a given matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the Matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] += this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5629. * @param ref matrix to store the result
  5630. */
  5631. Matrix.prototype.toNormalMatrix = function (ref) {
  5632. this.invertToRef(ref);
  5633. ref.transpose();
  5634. var m = ref.m;
  5635. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5636. };
  5637. /**
  5638. * Gets only rotation part of the current matrix
  5639. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5640. */
  5641. Matrix.prototype.getRotationMatrix = function () {
  5642. var result = Matrix.Identity();
  5643. this.getRotationMatrixToRef(result);
  5644. return result;
  5645. };
  5646. /**
  5647. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5648. * @param result defines the target matrix to store data to
  5649. * @returns the current matrix
  5650. */
  5651. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5652. var m = this.m;
  5653. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5654. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5655. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5656. if (this.determinant() <= 0) {
  5657. sy *= -1;
  5658. }
  5659. if (sx === 0 || sy === 0 || sz === 0) {
  5660. Matrix.IdentityToRef(result);
  5661. }
  5662. else {
  5663. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5664. }
  5665. return this;
  5666. };
  5667. // Statics
  5668. /**
  5669. * Creates a matrix from an array
  5670. * @param array defines the source array
  5671. * @param offset defines an offset in the source array
  5672. * @returns a new Matrix set from the starting index of the given array
  5673. */
  5674. Matrix.FromArray = function (array, offset) {
  5675. var result = new Matrix();
  5676. if (!offset) {
  5677. offset = 0;
  5678. }
  5679. Matrix.FromArrayToRef(array, offset, result);
  5680. return result;
  5681. };
  5682. /**
  5683. * Copy the content of an array into a given matrix
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @param result defines the target matrix
  5687. */
  5688. Matrix.FromArrayToRef = function (array, offset, result) {
  5689. for (var index = 0; index < 16; index++) {
  5690. result.m[index] = array[index + offset];
  5691. }
  5692. result._markAsUpdated();
  5693. };
  5694. /**
  5695. * Stores an array into a matrix after having multiplied each component by a given factor
  5696. * @param array defines the source array
  5697. * @param offset defines the offset in the source array
  5698. * @param scale defines the scaling factor
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset] * scale;
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores a list of values (16) inside a given matrix
  5709. * @param initialM11 defines 1st value of 1st row
  5710. * @param initialM12 defines 2nd value of 1st row
  5711. * @param initialM13 defines 3rd value of 1st row
  5712. * @param initialM14 defines 4th value of 1st row
  5713. * @param initialM21 defines 1st value of 2nd row
  5714. * @param initialM22 defines 2nd value of 2nd row
  5715. * @param initialM23 defines 3rd value of 2nd row
  5716. * @param initialM24 defines 4th value of 2nd row
  5717. * @param initialM31 defines 1st value of 3rd row
  5718. * @param initialM32 defines 2nd value of 3rd row
  5719. * @param initialM33 defines 3rd value of 3rd row
  5720. * @param initialM34 defines 4th value of 3rd row
  5721. * @param initialM41 defines 1st value of 4th row
  5722. * @param initialM42 defines 2nd value of 4th row
  5723. * @param initialM43 defines 3rd value of 4th row
  5724. * @param initialM44 defines 4th value of 4th row
  5725. * @param result defines the target matrix
  5726. */
  5727. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5728. result.m[0] = initialM11;
  5729. result.m[1] = initialM12;
  5730. result.m[2] = initialM13;
  5731. result.m[3] = initialM14;
  5732. result.m[4] = initialM21;
  5733. result.m[5] = initialM22;
  5734. result.m[6] = initialM23;
  5735. result.m[7] = initialM24;
  5736. result.m[8] = initialM31;
  5737. result.m[9] = initialM32;
  5738. result.m[10] = initialM33;
  5739. result.m[11] = initialM34;
  5740. result.m[12] = initialM41;
  5741. result.m[13] = initialM42;
  5742. result.m[14] = initialM43;
  5743. result.m[15] = initialM44;
  5744. result._markAsUpdated();
  5745. };
  5746. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5747. /**
  5748. * Gets an identity matrix that must not be updated
  5749. */
  5750. get: function () {
  5751. return Matrix._identityReadOnly;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. /**
  5757. * Creates new matrix from a list of values (16)
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @returns the new matrix
  5775. */
  5776. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5777. var result = new Matrix();
  5778. result.m[0] = initialM11;
  5779. result.m[1] = initialM12;
  5780. result.m[2] = initialM13;
  5781. result.m[3] = initialM14;
  5782. result.m[4] = initialM21;
  5783. result.m[5] = initialM22;
  5784. result.m[6] = initialM23;
  5785. result.m[7] = initialM24;
  5786. result.m[8] = initialM31;
  5787. result.m[9] = initialM32;
  5788. result.m[10] = initialM33;
  5789. result.m[11] = initialM34;
  5790. result.m[12] = initialM41;
  5791. result.m[13] = initialM42;
  5792. result.m[14] = initialM43;
  5793. result.m[15] = initialM44;
  5794. return result;
  5795. };
  5796. /**
  5797. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5798. * @param scale defines the scale vector3
  5799. * @param rotation defines the rotation quaternion
  5800. * @param translation defines the translation vector3
  5801. * @returns a new matrix
  5802. */
  5803. Matrix.Compose = function (scale, rotation, translation) {
  5804. var result = Matrix.Identity();
  5805. Matrix.ComposeToRef(scale, rotation, translation, result);
  5806. return result;
  5807. };
  5808. /**
  5809. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5810. * @param scale defines the scale vector3
  5811. * @param rotation defines the rotation quaternion
  5812. * @param translation defines the translation vector3
  5813. * @param result defines the target matrix
  5814. */
  5815. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5816. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5817. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5818. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5819. result.setTranslation(translation);
  5820. };
  5821. /**
  5822. * Creates a new identity matrix
  5823. * @returns a new identity matrix
  5824. */
  5825. Matrix.Identity = function () {
  5826. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5827. };
  5828. /**
  5829. * Creates a new identity matrix and stores the result in a given matrix
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.IdentityToRef = function (result) {
  5833. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5834. };
  5835. /**
  5836. * Creates a new zero matrix
  5837. * @returns a new zero matrix
  5838. */
  5839. Matrix.Zero = function () {
  5840. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5841. };
  5842. /**
  5843. * Creates a new rotation matrix for "angle" radians around the X axis
  5844. * @param angle defines the angle (in radians) to use
  5845. * @return the new matrix
  5846. */
  5847. Matrix.RotationX = function (angle) {
  5848. var result = new Matrix();
  5849. Matrix.RotationXToRef(angle, result);
  5850. return result;
  5851. };
  5852. /**
  5853. * Creates a new matrix as the invert of a given matrix
  5854. * @param source defines the source matrix
  5855. * @returns the new matrix
  5856. */
  5857. Matrix.Invert = function (source) {
  5858. var result = new Matrix();
  5859. source.invertToRef(result);
  5860. return result;
  5861. };
  5862. /**
  5863. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5864. * @param angle defines the angle (in radians) to use
  5865. * @param result defines the target matrix
  5866. */
  5867. Matrix.RotationXToRef = function (angle, result) {
  5868. var s = Math.sin(angle);
  5869. var c = Math.cos(angle);
  5870. result.m[0] = 1.0;
  5871. result.m[15] = 1.0;
  5872. result.m[5] = c;
  5873. result.m[10] = c;
  5874. result.m[9] = -s;
  5875. result.m[6] = s;
  5876. result.m[1] = 0.0;
  5877. result.m[2] = 0.0;
  5878. result.m[3] = 0.0;
  5879. result.m[4] = 0.0;
  5880. result.m[7] = 0.0;
  5881. result.m[8] = 0.0;
  5882. result.m[11] = 0.0;
  5883. result.m[12] = 0.0;
  5884. result.m[13] = 0.0;
  5885. result.m[14] = 0.0;
  5886. result._markAsUpdated();
  5887. };
  5888. /**
  5889. * Creates a new rotation matrix for "angle" radians around the Y axis
  5890. * @param angle defines the angle (in radians) to use
  5891. * @return the new matrix
  5892. */
  5893. Matrix.RotationY = function (angle) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYToRef(angle, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5900. * @param angle defines the angle (in radians) to use
  5901. * @param result defines the target matrix
  5902. */
  5903. Matrix.RotationYToRef = function (angle, result) {
  5904. var s = Math.sin(angle);
  5905. var c = Math.cos(angle);
  5906. result.m[5] = 1.0;
  5907. result.m[15] = 1.0;
  5908. result.m[0] = c;
  5909. result.m[2] = -s;
  5910. result.m[8] = s;
  5911. result.m[10] = c;
  5912. result.m[1] = 0.0;
  5913. result.m[3] = 0.0;
  5914. result.m[4] = 0.0;
  5915. result.m[6] = 0.0;
  5916. result.m[7] = 0.0;
  5917. result.m[9] = 0.0;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result._markAsUpdated();
  5923. };
  5924. /**
  5925. * Creates a new rotation matrix for "angle" radians around the Z axis
  5926. * @param angle defines the angle (in radians) to use
  5927. * @return the new matrix
  5928. */
  5929. Matrix.RotationZ = function (angle) {
  5930. var result = new Matrix();
  5931. Matrix.RotationZToRef(angle, result);
  5932. return result;
  5933. };
  5934. /**
  5935. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5936. * @param angle defines the angle (in radians) to use
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.RotationZToRef = function (angle, result) {
  5940. var s = Math.sin(angle);
  5941. var c = Math.cos(angle);
  5942. result.m[10] = 1.0;
  5943. result.m[15] = 1.0;
  5944. result.m[0] = c;
  5945. result.m[1] = s;
  5946. result.m[4] = -s;
  5947. result.m[5] = c;
  5948. result.m[2] = 0.0;
  5949. result.m[3] = 0.0;
  5950. result.m[6] = 0.0;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = 0.0;
  5953. result.m[9] = 0.0;
  5954. result.m[11] = 0.0;
  5955. result.m[12] = 0.0;
  5956. result.m[13] = 0.0;
  5957. result.m[14] = 0.0;
  5958. result._markAsUpdated();
  5959. };
  5960. /**
  5961. * Creates a new rotation matrix for "angle" radians around the given axis
  5962. * @param axis defines the axis to use
  5963. * @param angle defines the angle (in radians) to use
  5964. * @return the new matrix
  5965. */
  5966. Matrix.RotationAxis = function (axis, angle) {
  5967. var result = Matrix.Zero();
  5968. Matrix.RotationAxisToRef(axis, angle, result);
  5969. return result;
  5970. };
  5971. /**
  5972. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5973. * @param axis defines the axis to use
  5974. * @param angle defines the angle (in radians) to use
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5978. var s = Math.sin(-angle);
  5979. var c = Math.cos(-angle);
  5980. var c1 = 1 - c;
  5981. axis.normalize();
  5982. result.m[0] = (axis.x * axis.x) * c1 + c;
  5983. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5984. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5985. result.m[3] = 0.0;
  5986. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5987. result.m[5] = (axis.y * axis.y) * c1 + c;
  5988. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5989. result.m[7] = 0.0;
  5990. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5991. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5992. result.m[10] = (axis.z * axis.z) * c1 + c;
  5993. result.m[11] = 0.0;
  5994. result.m[15] = 1.0;
  5995. result._markAsUpdated();
  5996. };
  5997. /**
  5998. * Creates a rotation matrix
  5999. * @param yaw defines the yaw angle in radians (Y axis)
  6000. * @param pitch defines the pitch angle in radians (X axis)
  6001. * @param roll defines the roll angle in radians (X axis)
  6002. * @returns the new rotation matrix
  6003. */
  6004. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6005. var result = new Matrix();
  6006. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Creates a rotation matrix and stores it in a given matrix
  6011. * @param yaw defines the yaw angle in radians (Y axis)
  6012. * @param pitch defines the pitch angle in radians (X axis)
  6013. * @param roll defines the roll angle in radians (X axis)
  6014. * @param result defines the target matrix
  6015. */
  6016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6018. this._tempQuaternion.toRotationMatrix(result);
  6019. };
  6020. /**
  6021. * Creates a scaling matrix
  6022. * @param x defines the scale factor on X axis
  6023. * @param y defines the scale factor on Y axis
  6024. * @param z defines the scale factor on Z axis
  6025. * @returns the new matrix
  6026. */
  6027. Matrix.Scaling = function (x, y, z) {
  6028. var result = Matrix.Zero();
  6029. Matrix.ScalingToRef(x, y, z, result);
  6030. return result;
  6031. };
  6032. /**
  6033. * Creates a scaling matrix and stores it in a given matrix
  6034. * @param x defines the scale factor on X axis
  6035. * @param y defines the scale factor on Y axis
  6036. * @param z defines the scale factor on Z axis
  6037. * @param result defines the target matrix
  6038. */
  6039. Matrix.ScalingToRef = function (x, y, z, result) {
  6040. result.m[0] = x;
  6041. result.m[1] = 0.0;
  6042. result.m[2] = 0.0;
  6043. result.m[3] = 0.0;
  6044. result.m[4] = 0.0;
  6045. result.m[5] = y;
  6046. result.m[6] = 0.0;
  6047. result.m[7] = 0.0;
  6048. result.m[8] = 0.0;
  6049. result.m[9] = 0.0;
  6050. result.m[10] = z;
  6051. result.m[11] = 0.0;
  6052. result.m[12] = 0.0;
  6053. result.m[13] = 0.0;
  6054. result.m[14] = 0.0;
  6055. result.m[15] = 1.0;
  6056. result._markAsUpdated();
  6057. };
  6058. /**
  6059. * Creates a translation matrix
  6060. * @param x defines the translation on X axis
  6061. * @param y defines the translation on Y axis
  6062. * @param z defines the translationon Z axis
  6063. * @returns the new matrix
  6064. */
  6065. Matrix.Translation = function (x, y, z) {
  6066. var result = Matrix.Identity();
  6067. Matrix.TranslationToRef(x, y, z, result);
  6068. return result;
  6069. };
  6070. /**
  6071. * Creates a translation matrix and stores it in a given matrix
  6072. * @param x defines the translation on X axis
  6073. * @param y defines the translation on Y axis
  6074. * @param z defines the translationon Z axis
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.TranslationToRef = function (x, y, z, result) {
  6078. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6079. };
  6080. /**
  6081. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6082. * @param startValue defines the start value
  6083. * @param endValue defines the end value
  6084. * @param gradient defines the gradient factor
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.Lerp = function (startValue, endValue, gradient) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6094. * @param startValue defines the start value
  6095. * @param endValue defines the end value
  6096. * @param gradient defines the gradient factor
  6097. * @param result defines the Matrix object where to store data
  6098. */
  6099. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6100. for (var index = 0; index < 16; index++) {
  6101. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6102. }
  6103. result._markAsUpdated();
  6104. };
  6105. /**
  6106. * Builds a new matrix whose values are computed by:
  6107. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6108. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6109. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6110. * @param startValue defines the first matrix
  6111. * @param endValue defines the second matrix
  6112. * @param gradient defines the gradient between the two matrices
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6116. var result = Matrix.Zero();
  6117. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Update a matrix to values which are computed by:
  6122. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6123. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6124. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6125. * @param startValue defines the first matrix
  6126. * @param endValue defines the second matrix
  6127. * @param gradient defines the gradient between the two matrices
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6131. var startScale = MathTmp.Vector3[0];
  6132. var startRotation = MathTmp.Quaternion[0];
  6133. var startTranslation = MathTmp.Vector3[1];
  6134. startValue.decompose(startScale, startRotation, startTranslation);
  6135. var endScale = MathTmp.Vector3[2];
  6136. var endRotation = MathTmp.Quaternion[1];
  6137. var endTranslation = MathTmp.Vector3[3];
  6138. endValue.decompose(endScale, endRotation, endTranslation);
  6139. var resultScale = MathTmp.Vector3[4];
  6140. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6141. var resultRotation = MathTmp.Quaternion[2];
  6142. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6143. var resultTranslation = MathTmp.Vector3[5];
  6144. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6145. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6146. };
  6147. /**
  6148. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6149. * This function works in left handed mode
  6150. * @param eye defines the final position of the entity
  6151. * @param target defines where the entity should look at
  6152. * @param up defines the up vector for the entity
  6153. * @returns the new matrix
  6154. */
  6155. Matrix.LookAtLH = function (eye, target, up) {
  6156. var result = Matrix.Zero();
  6157. Matrix.LookAtLHToRef(eye, target, up, result);
  6158. return result;
  6159. };
  6160. /**
  6161. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6169. // Z axis
  6170. target.subtractToRef(eye, this._zAxis);
  6171. this._zAxis.normalize();
  6172. // X axis
  6173. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6174. if (this._xAxis.lengthSquared() === 0) {
  6175. this._xAxis.x = 1.0;
  6176. }
  6177. else {
  6178. this._xAxis.normalize();
  6179. }
  6180. // Y axis
  6181. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6182. this._yAxis.normalize();
  6183. // Eye angles
  6184. var ex = -Vector3.Dot(this._xAxis, eye);
  6185. var ey = -Vector3.Dot(this._yAxis, eye);
  6186. var ez = -Vector3.Dot(this._zAxis, eye);
  6187. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6188. };
  6189. /**
  6190. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6191. * This function works in right handed mode
  6192. * @param eye defines the final position of the entity
  6193. * @param target defines where the entity should look at
  6194. * @param up defines the up vector for the entity
  6195. * @returns the new matrix
  6196. */
  6197. Matrix.LookAtRH = function (eye, target, up) {
  6198. var result = Matrix.Zero();
  6199. Matrix.LookAtRHToRef(eye, target, up, result);
  6200. return result;
  6201. };
  6202. /**
  6203. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @param result defines the target matrix
  6209. */
  6210. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6211. // Z axis
  6212. eye.subtractToRef(target, this._zAxis);
  6213. this._zAxis.normalize();
  6214. // X axis
  6215. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6216. if (this._xAxis.lengthSquared() === 0) {
  6217. this._xAxis.x = 1.0;
  6218. }
  6219. else {
  6220. this._xAxis.normalize();
  6221. }
  6222. // Y axis
  6223. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6224. this._yAxis.normalize();
  6225. // Eye angles
  6226. var ex = -Vector3.Dot(this._xAxis, eye);
  6227. var ey = -Vector3.Dot(this._yAxis, eye);
  6228. var ez = -Vector3.Dot(this._zAxis, eye);
  6229. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6230. };
  6231. /**
  6232. * Create a left-handed orthographic projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Store a left-handed orthographic projection to a given matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @param result defines the target matrix
  6251. */
  6252. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6253. var n = znear;
  6254. var f = zfar;
  6255. var a = 2.0 / width;
  6256. var b = 2.0 / height;
  6257. var c = 2.0 / (f - n);
  6258. var d = -(f + n) / (f - n);
  6259. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6260. };
  6261. /**
  6262. * Create a left-handed orthographic projection matrix
  6263. * @param left defines the viewport left coordinate
  6264. * @param right defines the viewport right coordinate
  6265. * @param bottom defines the viewport bottom coordinate
  6266. * @param top defines the viewport top coordinate
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @returns a new matrix as a left-handed orthographic projection matrix
  6270. */
  6271. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6272. var matrix = Matrix.Zero();
  6273. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6274. return matrix;
  6275. };
  6276. /**
  6277. * Stores a left-handed orthographic projection into a given matrix
  6278. * @param left defines the viewport left coordinate
  6279. * @param right defines the viewport right coordinate
  6280. * @param bottom defines the viewport bottom coordinate
  6281. * @param top defines the viewport top coordinate
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6287. var n = znear;
  6288. var f = zfar;
  6289. var a = 2.0 / (right - left);
  6290. var b = 2.0 / (top - bottom);
  6291. var c = 2.0 / (f - n);
  6292. var d = -(f + n) / (f - n);
  6293. var i0 = (left + right) / (left - right);
  6294. var i1 = (top + bottom) / (bottom - top);
  6295. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6296. };
  6297. /**
  6298. * Creates a right-handed orthographic projection matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a right-handed orthographic projection matrix
  6306. */
  6307. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6310. return matrix;
  6311. };
  6312. /**
  6313. * Stores a right-handed orthographic projection into a given matrix
  6314. * @param left defines the viewport left coordinate
  6315. * @param right defines the viewport right coordinate
  6316. * @param bottom defines the viewport bottom coordinate
  6317. * @param top defines the viewport top coordinate
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. */
  6322. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6323. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6324. result.m[10] *= -1.0;
  6325. };
  6326. /**
  6327. * Creates a left-handed perspective projection matrix
  6328. * @param width defines the viewport width
  6329. * @param height defines the viewport height
  6330. * @param znear defines the near clip plane
  6331. * @param zfar defines the far clip plane
  6332. * @returns a new matrix as a left-handed perspective projection matrix
  6333. */
  6334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6335. var matrix = Matrix.Zero();
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 * n / width;
  6339. var b = 2.0 * n / height;
  6340. var c = (f + n) / (f - n);
  6341. var d = -2.0 * f * n / (f - n);
  6342. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6343. return matrix;
  6344. };
  6345. /**
  6346. * Creates a left-handed perspective projection matrix
  6347. * @param fov defines the horizontal field of view
  6348. * @param aspect defines the aspect ratio
  6349. * @param znear defines the near clip plane
  6350. * @param zfar defines the far clip plane
  6351. * @returns a new matrix as a left-handed perspective projection matrix
  6352. */
  6353. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6354. var matrix = Matrix.Zero();
  6355. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Stores a left-handed perspective projection into a given matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @param result defines the target matrix
  6365. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6366. */
  6367. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6368. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6369. var n = znear;
  6370. var f = zfar;
  6371. var t = 1.0 / (Math.tan(fov * 0.5));
  6372. var a = isVerticalFovFixed ? (t / aspect) : t;
  6373. var b = isVerticalFovFixed ? t : (t * aspect);
  6374. var c = (f + n) / (f - n);
  6375. var d = -2.0 * f * n / (f - n);
  6376. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6377. };
  6378. /**
  6379. * Creates a right-handed perspective projection matrix
  6380. * @param fov defines the horizontal field of view
  6381. * @param aspect defines the aspect ratio
  6382. * @param znear defines the near clip plane
  6383. * @param zfar defines the far clip plane
  6384. * @returns a new matrix as a right-handed perspective projection matrix
  6385. */
  6386. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6387. var matrix = Matrix.Zero();
  6388. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6389. return matrix;
  6390. };
  6391. /**
  6392. * Stores a right-handed perspective projection into a given matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @param result defines the target matrix
  6398. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6399. */
  6400. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6401. //alternatively this could be expressed as:
  6402. // m = PerspectiveFovLHToRef
  6403. // m[10] *= -1.0;
  6404. // m[11] *= -1.0;
  6405. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6406. var n = znear;
  6407. var f = zfar;
  6408. var t = 1.0 / (Math.tan(fov * 0.5));
  6409. var a = isVerticalFovFixed ? (t / aspect) : t;
  6410. var b = isVerticalFovFixed ? t : (t * aspect);
  6411. var c = -(f + n) / (f - n);
  6412. var d = -2 * f * n / (f - n);
  6413. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6414. };
  6415. /**
  6416. * Stores a perspective projection for WebVR info a given matrix
  6417. * @param fov defines the field of view
  6418. * @param znear defines the near clip plane
  6419. * @param zfar defines the far clip plane
  6420. * @param result defines the target matrix
  6421. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6422. */
  6423. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6424. if (rightHanded === void 0) { rightHanded = false; }
  6425. var rightHandedFactor = rightHanded ? -1 : 1;
  6426. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6427. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6428. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6429. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6430. var xScale = 2.0 / (leftTan + rightTan);
  6431. var yScale = 2.0 / (upTan + downTan);
  6432. result.m[0] = xScale;
  6433. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6434. result.m[5] = yScale;
  6435. result.m[6] = result.m[7] = 0.0;
  6436. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6437. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6438. result.m[10] = -zfar / (znear - zfar);
  6439. result.m[11] = 1.0 * rightHandedFactor;
  6440. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6441. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6442. result._markAsUpdated();
  6443. };
  6444. /**
  6445. * Computes a complete transformation matrix
  6446. * @param viewport defines the viewport to use
  6447. * @param world defines the world matrix
  6448. * @param view defines the view matrix
  6449. * @param projection defines the projection matrix
  6450. * @param zmin defines the near clip plane
  6451. * @param zmax defines the far clip plane
  6452. * @returns the transformation matrix
  6453. */
  6454. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6455. var cw = viewport.width;
  6456. var ch = viewport.height;
  6457. var cx = viewport.x;
  6458. var cy = viewport.y;
  6459. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6460. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6461. };
  6462. /**
  6463. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6464. * @param matrix defines the matrix to use
  6465. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6466. */
  6467. Matrix.GetAsMatrix2x2 = function (matrix) {
  6468. return new Float32Array([
  6469. matrix.m[0], matrix.m[1],
  6470. matrix.m[4], matrix.m[5]
  6471. ]);
  6472. };
  6473. /**
  6474. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6475. * @param matrix defines the matrix to use
  6476. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6477. */
  6478. Matrix.GetAsMatrix3x3 = function (matrix) {
  6479. return new Float32Array([
  6480. matrix.m[0], matrix.m[1], matrix.m[2],
  6481. matrix.m[4], matrix.m[5], matrix.m[6],
  6482. matrix.m[8], matrix.m[9], matrix.m[10]
  6483. ]);
  6484. };
  6485. /**
  6486. * Compute the transpose of a given matrix
  6487. * @param matrix defines the matrix to transpose
  6488. * @returns the new matrix
  6489. */
  6490. Matrix.Transpose = function (matrix) {
  6491. var result = new Matrix();
  6492. Matrix.TransposeToRef(matrix, result);
  6493. return result;
  6494. };
  6495. /**
  6496. * Compute the transpose of a matrix and store it in a target matrix
  6497. * @param matrix defines the matrix to transpose
  6498. * @param result defines the target matrix
  6499. */
  6500. Matrix.TransposeToRef = function (matrix, result) {
  6501. result.m[0] = matrix.m[0];
  6502. result.m[1] = matrix.m[4];
  6503. result.m[2] = matrix.m[8];
  6504. result.m[3] = matrix.m[12];
  6505. result.m[4] = matrix.m[1];
  6506. result.m[5] = matrix.m[5];
  6507. result.m[6] = matrix.m[9];
  6508. result.m[7] = matrix.m[13];
  6509. result.m[8] = matrix.m[2];
  6510. result.m[9] = matrix.m[6];
  6511. result.m[10] = matrix.m[10];
  6512. result.m[11] = matrix.m[14];
  6513. result.m[12] = matrix.m[3];
  6514. result.m[13] = matrix.m[7];
  6515. result.m[14] = matrix.m[11];
  6516. result.m[15] = matrix.m[15];
  6517. };
  6518. /**
  6519. * Computes a reflection matrix from a plane
  6520. * @param plane defines the reflection plane
  6521. * @returns a new matrix
  6522. */
  6523. Matrix.Reflection = function (plane) {
  6524. var matrix = new Matrix();
  6525. Matrix.ReflectionToRef(plane, matrix);
  6526. return matrix;
  6527. };
  6528. /**
  6529. * Computes a reflection matrix from a plane
  6530. * @param plane defines the reflection plane
  6531. * @param result defines the target matrix
  6532. */
  6533. Matrix.ReflectionToRef = function (plane, result) {
  6534. plane.normalize();
  6535. var x = plane.normal.x;
  6536. var y = plane.normal.y;
  6537. var z = plane.normal.z;
  6538. var temp = -2 * x;
  6539. var temp2 = -2 * y;
  6540. var temp3 = -2 * z;
  6541. result.m[0] = (temp * x) + 1;
  6542. result.m[1] = temp2 * x;
  6543. result.m[2] = temp3 * x;
  6544. result.m[3] = 0.0;
  6545. result.m[4] = temp * y;
  6546. result.m[5] = (temp2 * y) + 1;
  6547. result.m[6] = temp3 * y;
  6548. result.m[7] = 0.0;
  6549. result.m[8] = temp * z;
  6550. result.m[9] = temp2 * z;
  6551. result.m[10] = (temp3 * z) + 1;
  6552. result.m[11] = 0.0;
  6553. result.m[12] = temp * plane.d;
  6554. result.m[13] = temp2 * plane.d;
  6555. result.m[14] = temp3 * plane.d;
  6556. result.m[15] = 1.0;
  6557. result._markAsUpdated();
  6558. };
  6559. /**
  6560. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6561. * @param xaxis defines the value of the 1st axis
  6562. * @param yaxis defines the value of the 2nd axis
  6563. * @param zaxis defines the value of the 3rd axis
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6567. result.m[0] = xaxis.x;
  6568. result.m[1] = xaxis.y;
  6569. result.m[2] = xaxis.z;
  6570. result.m[3] = 0.0;
  6571. result.m[4] = yaxis.x;
  6572. result.m[5] = yaxis.y;
  6573. result.m[6] = yaxis.z;
  6574. result.m[7] = 0.0;
  6575. result.m[8] = zaxis.x;
  6576. result.m[9] = zaxis.y;
  6577. result.m[10] = zaxis.z;
  6578. result.m[11] = 0.0;
  6579. result.m[12] = 0.0;
  6580. result.m[13] = 0.0;
  6581. result.m[14] = 0.0;
  6582. result.m[15] = 1.0;
  6583. result._markAsUpdated();
  6584. };
  6585. /**
  6586. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6587. * @param quat defines the quaternion to use
  6588. * @param result defines the target matrix
  6589. */
  6590. Matrix.FromQuaternionToRef = function (quat, result) {
  6591. var xx = quat.x * quat.x;
  6592. var yy = quat.y * quat.y;
  6593. var zz = quat.z * quat.z;
  6594. var xy = quat.x * quat.y;
  6595. var zw = quat.z * quat.w;
  6596. var zx = quat.z * quat.x;
  6597. var yw = quat.y * quat.w;
  6598. var yz = quat.y * quat.z;
  6599. var xw = quat.x * quat.w;
  6600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6601. result.m[1] = 2.0 * (xy + zw);
  6602. result.m[2] = 2.0 * (zx - yw);
  6603. result.m[3] = 0.0;
  6604. result.m[4] = 2.0 * (xy - zw);
  6605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6606. result.m[6] = 2.0 * (yz + xw);
  6607. result.m[7] = 0.0;
  6608. result.m[8] = 2.0 * (zx + yw);
  6609. result.m[9] = 2.0 * (yz - xw);
  6610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6611. result.m[11] = 0.0;
  6612. result.m[12] = 0.0;
  6613. result.m[13] = 0.0;
  6614. result.m[14] = 0.0;
  6615. result.m[15] = 1.0;
  6616. result._markAsUpdated();
  6617. };
  6618. Matrix._tempQuaternion = new Quaternion();
  6619. Matrix._xAxis = Vector3.Zero();
  6620. Matrix._yAxis = Vector3.Zero();
  6621. Matrix._zAxis = Vector3.Zero();
  6622. Matrix._updateFlagSeed = 0;
  6623. Matrix._identityReadOnly = Matrix.Identity();
  6624. return Matrix;
  6625. }());
  6626. BABYLON.Matrix = Matrix;
  6627. var Plane = /** @class */ (function () {
  6628. /**
  6629. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6630. */
  6631. function Plane(a, b, c, d) {
  6632. this.normal = new Vector3(a, b, c);
  6633. this.d = d;
  6634. }
  6635. /**
  6636. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6637. */
  6638. Plane.prototype.asArray = function () {
  6639. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6640. };
  6641. // Methods
  6642. /**
  6643. * Returns a new plane copied from the current Plane.
  6644. */
  6645. Plane.prototype.clone = function () {
  6646. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6647. };
  6648. /**
  6649. * Returns the string "Plane".
  6650. */
  6651. Plane.prototype.getClassName = function () {
  6652. return "Plane";
  6653. };
  6654. /**
  6655. * Returns the Plane hash code.
  6656. */
  6657. Plane.prototype.getHashCode = function () {
  6658. var hash = this.normal.getHashCode();
  6659. hash = (hash * 397) ^ (this.d || 0);
  6660. return hash;
  6661. };
  6662. /**
  6663. * Normalize the current Plane in place.
  6664. * Returns the updated Plane.
  6665. */
  6666. Plane.prototype.normalize = function () {
  6667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6668. var magnitude = 0.0;
  6669. if (norm !== 0) {
  6670. magnitude = 1.0 / norm;
  6671. }
  6672. this.normal.x *= magnitude;
  6673. this.normal.y *= magnitude;
  6674. this.normal.z *= magnitude;
  6675. this.d *= magnitude;
  6676. return this;
  6677. };
  6678. /**
  6679. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6680. */
  6681. Plane.prototype.transform = function (transformation) {
  6682. var transposedMatrix = Matrix.Transpose(transformation);
  6683. var x = this.normal.x;
  6684. var y = this.normal.y;
  6685. var z = this.normal.z;
  6686. var d = this.d;
  6687. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6688. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6689. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6690. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6691. return new Plane(normalX, normalY, normalZ, finalD);
  6692. };
  6693. /**
  6694. * Returns the dot product (float) of the point coordinates and the plane normal.
  6695. */
  6696. Plane.prototype.dotCoordinate = function (point) {
  6697. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6698. };
  6699. /**
  6700. * Updates the current Plane from the plane defined by the three given points.
  6701. * Returns the updated Plane.
  6702. */
  6703. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6704. var x1 = point2.x - point1.x;
  6705. var y1 = point2.y - point1.y;
  6706. var z1 = point2.z - point1.z;
  6707. var x2 = point3.x - point1.x;
  6708. var y2 = point3.y - point1.y;
  6709. var z2 = point3.z - point1.z;
  6710. var yz = (y1 * z2) - (z1 * y2);
  6711. var xz = (z1 * x2) - (x1 * z2);
  6712. var xy = (x1 * y2) - (y1 * x2);
  6713. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6714. var invPyth;
  6715. if (pyth !== 0) {
  6716. invPyth = 1.0 / pyth;
  6717. }
  6718. else {
  6719. invPyth = 0.0;
  6720. }
  6721. this.normal.x = yz * invPyth;
  6722. this.normal.y = xz * invPyth;
  6723. this.normal.z = xy * invPyth;
  6724. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6725. return this;
  6726. };
  6727. /**
  6728. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6729. */
  6730. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6731. var dot = Vector3.Dot(this.normal, direction);
  6732. return (dot <= epsilon);
  6733. };
  6734. /**
  6735. * Returns the signed distance (float) from the given point to the Plane.
  6736. */
  6737. Plane.prototype.signedDistanceTo = function (point) {
  6738. return Vector3.Dot(point, this.normal) + this.d;
  6739. };
  6740. // Statics
  6741. /**
  6742. * Returns a new Plane from the given array.
  6743. */
  6744. Plane.FromArray = function (array) {
  6745. return new Plane(array[0], array[1], array[2], array[3]);
  6746. };
  6747. /**
  6748. * Returns a new Plane defined by the three given points.
  6749. */
  6750. Plane.FromPoints = function (point1, point2, point3) {
  6751. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6752. result.copyFromPoints(point1, point2, point3);
  6753. return result;
  6754. };
  6755. /**
  6756. * Returns a new Plane the normal vector to this plane at the given origin point.
  6757. * Note : the vector "normal" is updated because normalized.
  6758. */
  6759. Plane.FromPositionAndNormal = function (origin, normal) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. normal.normalize();
  6762. result.normal = normal;
  6763. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6764. return result;
  6765. };
  6766. /**
  6767. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6768. */
  6769. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6770. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6771. return Vector3.Dot(point, normal) + d;
  6772. };
  6773. return Plane;
  6774. }());
  6775. BABYLON.Plane = Plane;
  6776. var Viewport = /** @class */ (function () {
  6777. /**
  6778. * Creates a Viewport object located at (x, y) and sized (width, height).
  6779. */
  6780. function Viewport(x, y, width, height) {
  6781. this.x = x;
  6782. this.y = y;
  6783. this.width = width;
  6784. this.height = height;
  6785. }
  6786. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6787. if (renderWidthOrEngine.getRenderWidth) {
  6788. var engine = renderWidthOrEngine;
  6789. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6790. }
  6791. var renderWidth = renderWidthOrEngine;
  6792. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6793. };
  6794. /**
  6795. * Returns a new Viewport copied from the current one.
  6796. */
  6797. Viewport.prototype.clone = function () {
  6798. return new Viewport(this.x, this.y, this.width, this.height);
  6799. };
  6800. return Viewport;
  6801. }());
  6802. BABYLON.Viewport = Viewport;
  6803. var Frustum = /** @class */ (function () {
  6804. function Frustum() {
  6805. }
  6806. /**
  6807. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6808. */
  6809. Frustum.GetPlanes = function (transform) {
  6810. var frustumPlanes = [];
  6811. for (var index = 0; index < 6; index++) {
  6812. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6813. }
  6814. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6815. return frustumPlanes;
  6816. };
  6817. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6818. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6819. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6820. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6821. frustumPlane.d = transform.m[15] + transform.m[14];
  6822. frustumPlane.normalize();
  6823. };
  6824. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6825. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6826. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6827. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6828. frustumPlane.d = transform.m[15] - transform.m[14];
  6829. frustumPlane.normalize();
  6830. };
  6831. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6835. frustumPlane.d = transform.m[15] + transform.m[12];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6842. frustumPlane.d = transform.m[15] - transform.m[12];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6849. frustumPlane.d = transform.m[15] - transform.m[13];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6856. frustumPlane.d = transform.m[15] + transform.m[13];
  6857. frustumPlane.normalize();
  6858. };
  6859. /**
  6860. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6861. */
  6862. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6863. // Near
  6864. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6865. // Far
  6866. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6867. // Left
  6868. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6869. // Right
  6870. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6871. // Top
  6872. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6873. // Bottom
  6874. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6875. };
  6876. return Frustum;
  6877. }());
  6878. BABYLON.Frustum = Frustum;
  6879. /** Defines supported spaces */
  6880. var Space;
  6881. (function (Space) {
  6882. /** Local (object) space */
  6883. Space[Space["LOCAL"] = 0] = "LOCAL";
  6884. /** World space */
  6885. Space[Space["WORLD"] = 1] = "WORLD";
  6886. /** Bone space */
  6887. Space[Space["BONE"] = 2] = "BONE";
  6888. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6889. /** Defines the 3 main axes */
  6890. var Axis = /** @class */ (function () {
  6891. function Axis() {
  6892. }
  6893. /** X axis */
  6894. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6895. /** Y axis */
  6896. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6897. /** Z axis */
  6898. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6899. return Axis;
  6900. }());
  6901. BABYLON.Axis = Axis;
  6902. ;
  6903. var BezierCurve = /** @class */ (function () {
  6904. function BezierCurve() {
  6905. }
  6906. /**
  6907. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6908. */
  6909. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6910. // Extract X (which is equal to time here)
  6911. var f0 = 1 - 3 * x2 + 3 * x1;
  6912. var f1 = 3 * x2 - 6 * x1;
  6913. var f2 = 3 * x1;
  6914. var refinedT = t;
  6915. for (var i = 0; i < 5; i++) {
  6916. var refinedT2 = refinedT * refinedT;
  6917. var refinedT3 = refinedT2 * refinedT;
  6918. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6919. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6920. refinedT -= (x - t) * slope;
  6921. refinedT = Math.min(1, Math.max(0, refinedT));
  6922. }
  6923. // Resolve cubic bezier for the given x
  6924. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6925. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6926. Math.pow(refinedT, 3);
  6927. };
  6928. return BezierCurve;
  6929. }());
  6930. BABYLON.BezierCurve = BezierCurve;
  6931. /**
  6932. * Defines potential orientation for back face culling
  6933. */
  6934. var Orientation;
  6935. (function (Orientation) {
  6936. /**
  6937. * Clockwise
  6938. */
  6939. Orientation[Orientation["CW"] = 0] = "CW";
  6940. /** Counter clockwise */
  6941. Orientation[Orientation["CCW"] = 1] = "CCW";
  6942. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6943. /**
  6944. * Defines angle representation
  6945. */
  6946. var Angle = /** @class */ (function () {
  6947. /**
  6948. * Creates an Angle object of "radians" radians (float).
  6949. */
  6950. function Angle(radians) {
  6951. this._radians = radians;
  6952. if (this._radians < 0.0)
  6953. this._radians += (2.0 * Math.PI);
  6954. }
  6955. /**
  6956. * Get value in degrees
  6957. * @returns the Angle value in degrees (float)
  6958. */
  6959. Angle.prototype.degrees = function () {
  6960. return this._radians * 180.0 / Math.PI;
  6961. };
  6962. /**
  6963. * Get value in radians
  6964. * @returns the Angle value in radians (float)
  6965. */
  6966. Angle.prototype.radians = function () {
  6967. return this._radians;
  6968. };
  6969. /**
  6970. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6971. * @param a defines first vector
  6972. * @param b defines second vector
  6973. * @returns a new Angle
  6974. */
  6975. Angle.BetweenTwoPoints = function (a, b) {
  6976. var delta = b.subtract(a);
  6977. var theta = Math.atan2(delta.y, delta.x);
  6978. return new Angle(theta);
  6979. };
  6980. /**
  6981. * Gets a new Angle object from the given float in radians
  6982. * @param radians defines the angle value in radians
  6983. * @returns a new Angle
  6984. */
  6985. Angle.FromRadians = function (radians) {
  6986. return new Angle(radians);
  6987. };
  6988. /**
  6989. * Gets a new Angle object from the given float in degrees
  6990. * @param degrees defines the angle value in degrees
  6991. * @returns a new Angle
  6992. */
  6993. Angle.FromDegrees = function (degrees) {
  6994. return new Angle(degrees * Math.PI / 180.0);
  6995. };
  6996. return Angle;
  6997. }());
  6998. BABYLON.Angle = Angle;
  6999. var Arc2 = /** @class */ (function () {
  7000. /**
  7001. * Creates an Arc object from the three given points : start, middle and end.
  7002. */
  7003. function Arc2(startPoint, midPoint, endPoint) {
  7004. this.startPoint = startPoint;
  7005. this.midPoint = midPoint;
  7006. this.endPoint = endPoint;
  7007. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7008. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7009. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7010. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7011. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7012. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7013. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7014. var a1 = this.startAngle.degrees();
  7015. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7016. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7017. // angles correction
  7018. if (a2 - a1 > +180.0)
  7019. a2 -= 360.0;
  7020. if (a2 - a1 < -180.0)
  7021. a2 += 360.0;
  7022. if (a3 - a2 > +180.0)
  7023. a3 -= 360.0;
  7024. if (a3 - a2 < -180.0)
  7025. a3 += 360.0;
  7026. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7027. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7028. }
  7029. return Arc2;
  7030. }());
  7031. BABYLON.Arc2 = Arc2;
  7032. var Path2 = /** @class */ (function () {
  7033. /**
  7034. * Creates a Path2 object from the starting 2D coordinates x and y.
  7035. */
  7036. function Path2(x, y) {
  7037. this._points = new Array();
  7038. this._length = 0.0;
  7039. this.closed = false;
  7040. this._points.push(new Vector2(x, y));
  7041. }
  7042. /**
  7043. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7044. * Returns the updated Path2.
  7045. */
  7046. Path2.prototype.addLineTo = function (x, y) {
  7047. if (this.closed) {
  7048. return this;
  7049. }
  7050. var newPoint = new Vector2(x, y);
  7051. var previousPoint = this._points[this._points.length - 1];
  7052. this._points.push(newPoint);
  7053. this._length += newPoint.subtract(previousPoint).length();
  7054. return this;
  7055. };
  7056. /**
  7057. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7061. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7062. if (this.closed) {
  7063. return this;
  7064. }
  7065. var startPoint = this._points[this._points.length - 1];
  7066. var midPoint = new Vector2(midX, midY);
  7067. var endPoint = new Vector2(endX, endY);
  7068. var arc = new Arc2(startPoint, midPoint, endPoint);
  7069. var increment = arc.angle.radians() / numberOfSegments;
  7070. if (arc.orientation === Orientation.CW)
  7071. increment *= -1;
  7072. var currentAngle = arc.startAngle.radians() + increment;
  7073. for (var i = 0; i < numberOfSegments; i++) {
  7074. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7075. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7076. this.addLineTo(x, y);
  7077. currentAngle += increment;
  7078. }
  7079. return this;
  7080. };
  7081. /**
  7082. * Closes the Path2.
  7083. * Returns the Path2.
  7084. */
  7085. Path2.prototype.close = function () {
  7086. this.closed = true;
  7087. return this;
  7088. };
  7089. /**
  7090. * Returns the Path2 total length (float).
  7091. */
  7092. Path2.prototype.length = function () {
  7093. var result = this._length;
  7094. if (!this.closed) {
  7095. var lastPoint = this._points[this._points.length - 1];
  7096. var firstPoint = this._points[0];
  7097. result += (firstPoint.subtract(lastPoint).length());
  7098. }
  7099. return result;
  7100. };
  7101. /**
  7102. * Returns the Path2 internal array of points.
  7103. */
  7104. Path2.prototype.getPoints = function () {
  7105. return this._points;
  7106. };
  7107. /**
  7108. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7109. */
  7110. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7111. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7112. return Vector2.Zero();
  7113. }
  7114. var lengthPosition = normalizedLengthPosition * this.length();
  7115. var previousOffset = 0;
  7116. for (var i = 0; i < this._points.length; i++) {
  7117. var j = (i + 1) % this._points.length;
  7118. var a = this._points[i];
  7119. var b = this._points[j];
  7120. var bToA = b.subtract(a);
  7121. var nextOffset = (bToA.length() + previousOffset);
  7122. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7123. var dir = bToA.normalize();
  7124. var localOffset = lengthPosition - previousOffset;
  7125. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7126. }
  7127. previousOffset = nextOffset;
  7128. }
  7129. return Vector2.Zero();
  7130. };
  7131. /**
  7132. * Returns a new Path2 starting at the coordinates (x, y).
  7133. */
  7134. Path2.StartingAt = function (x, y) {
  7135. return new Path2(x, y);
  7136. };
  7137. return Path2;
  7138. }());
  7139. BABYLON.Path2 = Path2;
  7140. var Path3D = /** @class */ (function () {
  7141. /**
  7142. * new Path3D(path, normal, raw)
  7143. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7144. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7145. * path : an array of Vector3, the curve axis of the Path3D
  7146. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7147. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7148. */
  7149. function Path3D(path, firstNormal, raw) {
  7150. if (firstNormal === void 0) { firstNormal = null; }
  7151. this.path = path;
  7152. this._curve = new Array();
  7153. this._distances = new Array();
  7154. this._tangents = new Array();
  7155. this._normals = new Array();
  7156. this._binormals = new Array();
  7157. for (var p = 0; p < path.length; p++) {
  7158. this._curve[p] = path[p].clone(); // hard copy
  7159. }
  7160. this._raw = raw || false;
  7161. this._compute(firstNormal);
  7162. }
  7163. /**
  7164. * Returns the Path3D array of successive Vector3 designing its curve.
  7165. */
  7166. Path3D.prototype.getCurve = function () {
  7167. return this._curve;
  7168. };
  7169. /**
  7170. * Returns an array populated with tangent vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getTangents = function () {
  7173. return this._tangents;
  7174. };
  7175. /**
  7176. * Returns an array populated with normal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getNormals = function () {
  7179. return this._normals;
  7180. };
  7181. /**
  7182. * Returns an array populated with binormal vectors on each Path3D curve point.
  7183. */
  7184. Path3D.prototype.getBinormals = function () {
  7185. return this._binormals;
  7186. };
  7187. /**
  7188. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7189. */
  7190. Path3D.prototype.getDistances = function () {
  7191. return this._distances;
  7192. };
  7193. /**
  7194. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7195. * Returns the same object updated.
  7196. */
  7197. Path3D.prototype.update = function (path, firstNormal) {
  7198. if (firstNormal === void 0) { firstNormal = null; }
  7199. for (var p = 0; p < path.length; p++) {
  7200. this._curve[p].x = path[p].x;
  7201. this._curve[p].y = path[p].y;
  7202. this._curve[p].z = path[p].z;
  7203. }
  7204. this._compute(firstNormal);
  7205. return this;
  7206. };
  7207. // private function compute() : computes tangents, normals and binormals
  7208. Path3D.prototype._compute = function (firstNormal) {
  7209. var l = this._curve.length;
  7210. // first and last tangents
  7211. this._tangents[0] = this._getFirstNonNullVector(0);
  7212. if (!this._raw) {
  7213. this._tangents[0].normalize();
  7214. }
  7215. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7216. if (!this._raw) {
  7217. this._tangents[l - 1].normalize();
  7218. }
  7219. // normals and binormals at first point : arbitrary vector with _normalVector()
  7220. var tg0 = this._tangents[0];
  7221. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7222. this._normals[0] = pp0;
  7223. if (!this._raw) {
  7224. this._normals[0].normalize();
  7225. }
  7226. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7227. if (!this._raw) {
  7228. this._binormals[0].normalize();
  7229. }
  7230. this._distances[0] = 0.0;
  7231. // normals and binormals : next points
  7232. var prev; // previous vector (segment)
  7233. var cur; // current vector (segment)
  7234. var curTang; // current tangent
  7235. // previous normal
  7236. var prevBinor; // previous binormal
  7237. for (var i = 1; i < l; i++) {
  7238. // tangents
  7239. prev = this._getLastNonNullVector(i);
  7240. if (i < l - 1) {
  7241. cur = this._getFirstNonNullVector(i);
  7242. this._tangents[i] = prev.add(cur);
  7243. this._tangents[i].normalize();
  7244. }
  7245. this._distances[i] = this._distances[i - 1] + prev.length();
  7246. // normals and binormals
  7247. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7248. curTang = this._tangents[i];
  7249. prevBinor = this._binormals[i - 1];
  7250. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7251. if (!this._raw) {
  7252. this._normals[i].normalize();
  7253. }
  7254. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7255. if (!this._raw) {
  7256. this._binormals[i].normalize();
  7257. }
  7258. }
  7259. };
  7260. // private function getFirstNonNullVector(index)
  7261. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7262. Path3D.prototype._getFirstNonNullVector = function (index) {
  7263. var i = 1;
  7264. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7266. i++;
  7267. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7268. }
  7269. return nNVector;
  7270. };
  7271. // private function getLastNonNullVector(index)
  7272. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7273. Path3D.prototype._getLastNonNullVector = function (index) {
  7274. var i = 1;
  7275. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. while (nLVector.length() === 0 && index > i + 1) {
  7277. i++;
  7278. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7279. }
  7280. return nLVector;
  7281. };
  7282. // private function normalVector(v0, vt, va) :
  7283. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7284. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7285. Path3D.prototype._normalVector = function (v0, vt, va) {
  7286. var normal0;
  7287. var tgl = vt.length();
  7288. if (tgl === 0.0) {
  7289. tgl = 1.0;
  7290. }
  7291. if (va === undefined || va === null) {
  7292. var point;
  7293. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7294. point = new Vector3(0.0, -1.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(1.0, 0.0, 0.0);
  7298. }
  7299. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7300. point = new Vector3(0.0, 0.0, 1.0);
  7301. }
  7302. else {
  7303. point = Vector3.Zero();
  7304. }
  7305. normal0 = Vector3.Cross(vt, point);
  7306. }
  7307. else {
  7308. normal0 = Vector3.Cross(vt, va);
  7309. Vector3.CrossToRef(normal0, vt, normal0);
  7310. }
  7311. normal0.normalize();
  7312. return normal0;
  7313. };
  7314. return Path3D;
  7315. }());
  7316. BABYLON.Path3D = Path3D;
  7317. var Curve3 = /** @class */ (function () {
  7318. /**
  7319. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7320. * A Curve3 is designed from a series of successive Vector3.
  7321. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7322. */
  7323. function Curve3(points) {
  7324. this._length = 0.0;
  7325. this._points = points;
  7326. this._length = this._computeLength(points);
  7327. }
  7328. /**
  7329. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7330. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7331. * @param v1 (Vector3) the control point
  7332. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7333. * @param nbPoints (integer) the wanted number of points in the curve
  7334. */
  7335. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7336. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7337. var bez = new Array();
  7338. var equation = function (t, val0, val1, val2) {
  7339. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7340. return res;
  7341. };
  7342. for (var i = 0; i <= nbPoints; i++) {
  7343. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7344. }
  7345. return new Curve3(bez);
  7346. };
  7347. /**
  7348. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7349. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7350. * @param v1 (Vector3) the first control point
  7351. * @param v2 (Vector3) the second control point
  7352. * @param v3 (Vector3) the end point of the Cubic Bezier
  7353. * @param nbPoints (integer) the wanted number of points in the curve
  7354. */
  7355. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7356. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7357. var bez = new Array();
  7358. var equation = function (t, val0, val1, val2, val3) {
  7359. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7360. return res;
  7361. };
  7362. for (var i = 0; i <= nbPoints; i++) {
  7363. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7364. }
  7365. return new Curve3(bez);
  7366. };
  7367. /**
  7368. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7369. * @param p1 (Vector3) the origin point of the Hermite Spline
  7370. * @param t1 (Vector3) the tangent vector at the origin point
  7371. * @param p2 (Vector3) the end point of the Hermite Spline
  7372. * @param t2 (Vector3) the tangent vector at the end point
  7373. * @param nbPoints (integer) the wanted number of points in the curve
  7374. */
  7375. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7376. var hermite = new Array();
  7377. var step = 1.0 / nbPoints;
  7378. for (var i = 0; i <= nbPoints; i++) {
  7379. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7380. }
  7381. return new Curve3(hermite);
  7382. };
  7383. /**
  7384. * Returns a Curve3 object along a CatmullRom Spline curve :
  7385. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7386. * @param nbPoints (integer) the wanted number of points between each curve control points
  7387. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7388. */
  7389. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7390. var catmullRom = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. var amount = 0.0;
  7393. if (closed) {
  7394. var pointsCount = points.length;
  7395. for (var i = 0; i < pointsCount; i++) {
  7396. amount = 0;
  7397. for (var c = 0; c < nbPoints; c++) {
  7398. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7399. amount += step;
  7400. }
  7401. }
  7402. catmullRom.push(catmullRom[0]);
  7403. }
  7404. else {
  7405. var totalPoints = new Array();
  7406. totalPoints.push(points[0].clone());
  7407. Array.prototype.push.apply(totalPoints, points);
  7408. totalPoints.push(points[points.length - 1].clone());
  7409. for (var i = 0; i < totalPoints.length - 3; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. i--;
  7417. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7418. }
  7419. return new Curve3(catmullRom);
  7420. };
  7421. /**
  7422. * Returns the Curve3 stored array of successive Vector3
  7423. */
  7424. Curve3.prototype.getPoints = function () {
  7425. return this._points;
  7426. };
  7427. /**
  7428. * Returns the computed length (float) of the curve.
  7429. */
  7430. Curve3.prototype.length = function () {
  7431. return this._length;
  7432. };
  7433. /**
  7434. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7435. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7436. * curveA and curveB keep unchanged.
  7437. */
  7438. Curve3.prototype.continue = function (curve) {
  7439. var lastPoint = this._points[this._points.length - 1];
  7440. var continuedPoints = this._points.slice();
  7441. var curvePoints = curve.getPoints();
  7442. for (var i = 1; i < curvePoints.length; i++) {
  7443. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7444. }
  7445. var continuedCurve = new Curve3(continuedPoints);
  7446. return continuedCurve;
  7447. };
  7448. Curve3.prototype._computeLength = function (path) {
  7449. var l = 0;
  7450. for (var i = 1; i < path.length; i++) {
  7451. l += (path[i].subtract(path[i - 1])).length();
  7452. }
  7453. return l;
  7454. };
  7455. return Curve3;
  7456. }());
  7457. BABYLON.Curve3 = Curve3;
  7458. // Vertex formats
  7459. var PositionNormalVertex = /** @class */ (function () {
  7460. function PositionNormalVertex(position, normal) {
  7461. if (position === void 0) { position = Vector3.Zero(); }
  7462. if (normal === void 0) { normal = Vector3.Up(); }
  7463. this.position = position;
  7464. this.normal = normal;
  7465. }
  7466. PositionNormalVertex.prototype.clone = function () {
  7467. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7468. };
  7469. return PositionNormalVertex;
  7470. }());
  7471. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7472. var PositionNormalTextureVertex = /** @class */ (function () {
  7473. function PositionNormalTextureVertex(position, normal, uv) {
  7474. if (position === void 0) { position = Vector3.Zero(); }
  7475. if (normal === void 0) { normal = Vector3.Up(); }
  7476. if (uv === void 0) { uv = Vector2.Zero(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. this.uv = uv;
  7480. }
  7481. PositionNormalTextureVertex.prototype.clone = function () {
  7482. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7483. };
  7484. return PositionNormalTextureVertex;
  7485. }());
  7486. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7487. // Temporary pre-allocated objects for engine internal use
  7488. // usage in any internal function :
  7489. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7490. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7491. var Tmp = /** @class */ (function () {
  7492. function Tmp() {
  7493. }
  7494. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7495. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7496. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7497. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7498. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7499. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7500. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7501. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7502. Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7505. return Tmp;
  7506. }());
  7507. BABYLON.Tmp = Tmp;
  7508. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7509. var MathTmp = /** @class */ (function () {
  7510. function MathTmp() {
  7511. }
  7512. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7513. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7514. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7515. return MathTmp;
  7516. }());
  7517. })(BABYLON || (BABYLON = {}));
  7518. //# sourceMappingURL=babylon.math.js.map
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. var Scalar = /** @class */ (function () {
  7522. function Scalar() {
  7523. }
  7524. /**
  7525. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7526. */
  7527. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7528. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7529. var num = a - b;
  7530. return -epsilon <= num && num <= epsilon;
  7531. };
  7532. /**
  7533. * Returns a string : the upper case translation of the number i to hexadecimal.
  7534. */
  7535. Scalar.ToHex = function (i) {
  7536. var str = i.toString(16);
  7537. if (i <= 15) {
  7538. return ("0" + str).toUpperCase();
  7539. }
  7540. return str.toUpperCase();
  7541. };
  7542. /**
  7543. * Returns -1 if value is negative and +1 is value is positive.
  7544. * Returns the value itself if it's equal to zero.
  7545. */
  7546. Scalar.Sign = function (value) {
  7547. value = +value; // convert to a number
  7548. if (value === 0 || isNaN(value))
  7549. return value;
  7550. return value > 0 ? 1 : -1;
  7551. };
  7552. /**
  7553. * Returns the value itself if it's between min and max.
  7554. * Returns min if the value is lower than min.
  7555. * Returns max if the value is greater than max.
  7556. */
  7557. Scalar.Clamp = function (value, min, max) {
  7558. if (min === void 0) { min = 0; }
  7559. if (max === void 0) { max = 1; }
  7560. return Math.min(max, Math.max(min, value));
  7561. };
  7562. /**
  7563. * Returns the log2 of value.
  7564. */
  7565. Scalar.Log2 = function (value) {
  7566. return Math.log(value) * Math.LOG2E;
  7567. };
  7568. /**
  7569. * Loops the value, so that it is never larger than length and never smaller than 0.
  7570. *
  7571. * This is similar to the modulo operator but it works with floating point numbers.
  7572. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7573. * With t = 5 and length = 2.5, the result would be 0.0.
  7574. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7575. */
  7576. Scalar.Repeat = function (value, length) {
  7577. return value - Math.floor(value / length) * length;
  7578. };
  7579. /**
  7580. * Normalize the value between 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Normalize = function (value, min, max) {
  7583. return (value - min) / (max - min);
  7584. };
  7585. /**
  7586. * Denormalize the value from 0.0 and 1.0 using min and max values
  7587. */
  7588. Scalar.Denormalize = function (normalized, min, max) {
  7589. return (normalized * (max - min) + min);
  7590. };
  7591. /**
  7592. * Calculates the shortest difference between two given angles given in degrees.
  7593. */
  7594. Scalar.DeltaAngle = function (current, target) {
  7595. var num = Scalar.Repeat(target - current, 360.0);
  7596. if (num > 180.0) {
  7597. num -= 360.0;
  7598. }
  7599. return num;
  7600. };
  7601. /**
  7602. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7603. *
  7604. * The returned value will move back and forth between 0 and length
  7605. */
  7606. Scalar.PingPong = function (tx, length) {
  7607. var t = Scalar.Repeat(tx, length * 2.0);
  7608. return length - Math.abs(t - length);
  7609. };
  7610. /**
  7611. * Interpolates between min and max with smoothing at the limits.
  7612. *
  7613. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7614. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7615. */
  7616. Scalar.SmoothStep = function (from, to, tx) {
  7617. var t = Scalar.Clamp(tx);
  7618. t = -2.0 * t * t * t + 3.0 * t * t;
  7619. return to * t + from * (1.0 - t);
  7620. };
  7621. /**
  7622. * Moves a value current towards target.
  7623. *
  7624. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7625. * Negative values of maxDelta pushes the value away from target.
  7626. */
  7627. Scalar.MoveTowards = function (current, target, maxDelta) {
  7628. var result = 0;
  7629. if (Math.abs(target - current) <= maxDelta) {
  7630. result = target;
  7631. }
  7632. else {
  7633. result = current + Scalar.Sign(target - current) * maxDelta;
  7634. }
  7635. return result;
  7636. };
  7637. /**
  7638. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7639. *
  7640. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7641. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7642. */
  7643. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7644. var num = Scalar.DeltaAngle(current, target);
  7645. var result = 0;
  7646. if (-maxDelta < num && num < maxDelta) {
  7647. result = target;
  7648. }
  7649. else {
  7650. target = current + num;
  7651. result = Scalar.MoveTowards(current, target, maxDelta);
  7652. }
  7653. return result;
  7654. };
  7655. /**
  7656. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7657. */
  7658. Scalar.Lerp = function (start, end, amount) {
  7659. return start + ((end - start) * amount);
  7660. };
  7661. /**
  7662. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7663. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7664. */
  7665. Scalar.LerpAngle = function (start, end, amount) {
  7666. var num = Scalar.Repeat(end - start, 360.0);
  7667. if (num > 180.0) {
  7668. num -= 360.0;
  7669. }
  7670. return start + num * Scalar.Clamp(amount);
  7671. };
  7672. /**
  7673. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7674. */
  7675. Scalar.InverseLerp = function (a, b, value) {
  7676. var result = 0;
  7677. if (a != b) {
  7678. result = Scalar.Clamp((value - a) / (b - a));
  7679. }
  7680. else {
  7681. result = 0.0;
  7682. }
  7683. return result;
  7684. };
  7685. /**
  7686. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7687. */
  7688. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7689. var squared = amount * amount;
  7690. var cubed = amount * squared;
  7691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7693. var part3 = (cubed - (2.0 * squared)) + amount;
  7694. var part4 = cubed - squared;
  7695. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7696. };
  7697. /**
  7698. * Returns a random float number between and min and max values
  7699. */
  7700. Scalar.RandomRange = function (min, max) {
  7701. if (min === max)
  7702. return min;
  7703. return ((Math.random() * (max - min)) + min);
  7704. };
  7705. /**
  7706. * This function returns percentage of a number in a given range.
  7707. *
  7708. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7709. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7710. */
  7711. Scalar.RangeToPercent = function (number, min, max) {
  7712. return ((number - min) / (max - min));
  7713. };
  7714. /**
  7715. * This function returns number that corresponds to the percentage in a given range.
  7716. *
  7717. * PercentToRange(0.34,0,100) will return 34.
  7718. */
  7719. Scalar.PercentToRange = function (percent, min, max) {
  7720. return ((max - min) * percent + min);
  7721. };
  7722. /**
  7723. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7724. * @param angle The angle to normalize in radian.
  7725. * @return The converted angle.
  7726. */
  7727. Scalar.NormalizeRadians = function (angle) {
  7728. // More precise but slower version kept for reference.
  7729. // angle = angle % Tools.TwoPi;
  7730. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7731. //if (angle > Math.PI) {
  7732. // angle -= Tools.TwoPi;
  7733. //}
  7734. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7735. return angle;
  7736. };
  7737. /**
  7738. * Two pi constants convenient for computation.
  7739. */
  7740. Scalar.TwoPi = Math.PI * 2;
  7741. return Scalar;
  7742. }());
  7743. BABYLON.Scalar = Scalar;
  7744. })(BABYLON || (BABYLON = {}));
  7745. //# sourceMappingURL=babylon.math.scalar.js.map
  7746. //# sourceMappingURL=babylon.mixins.js.map
  7747. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7748. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7749. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7750. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7751. //# sourceMappingURL=babylon.webgl2.js.map
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var __decoratorInitialStore = {};
  7755. var __mergedStore = {};
  7756. var _copySource = function (creationFunction, source, instanciate) {
  7757. var destination = creationFunction();
  7758. // Tags
  7759. if (BABYLON.Tags) {
  7760. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7761. }
  7762. var classStore = getMergedStore(destination);
  7763. // Properties
  7764. for (var property in classStore) {
  7765. var propertyDescriptor = classStore[property];
  7766. var sourceProperty = source[property];
  7767. var propertyType = propertyDescriptor.type;
  7768. if (sourceProperty !== undefined && sourceProperty !== null) {
  7769. switch (propertyType) {
  7770. case 0: // Value
  7771. case 6: // Mesh reference
  7772. case 11: // Camera reference
  7773. destination[property] = sourceProperty;
  7774. break;
  7775. case 1: // Texture
  7776. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7777. break;
  7778. case 2: // Color3
  7779. case 3: // FresnelParameters
  7780. case 4: // Vector2
  7781. case 5: // Vector3
  7782. case 7: // Color Curves
  7783. case 10: // Quaternion
  7784. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. }
  7787. }
  7788. }
  7789. return destination;
  7790. };
  7791. function getDirectStore(target) {
  7792. var classKey = target.getClassName();
  7793. if (!__decoratorInitialStore[classKey]) {
  7794. __decoratorInitialStore[classKey] = {};
  7795. }
  7796. return __decoratorInitialStore[classKey];
  7797. }
  7798. /**
  7799. * Return the list of properties flagged as serializable
  7800. * @param target: host object
  7801. */
  7802. function getMergedStore(target) {
  7803. var classKey = target.getClassName();
  7804. if (__mergedStore[classKey]) {
  7805. return __mergedStore[classKey];
  7806. }
  7807. __mergedStore[classKey] = {};
  7808. var store = __mergedStore[classKey];
  7809. var currentTarget = target;
  7810. var currentKey = classKey;
  7811. while (currentKey) {
  7812. var initialStore = __decoratorInitialStore[currentKey];
  7813. for (var property in initialStore) {
  7814. store[property] = initialStore[property];
  7815. }
  7816. var parent_1 = void 0;
  7817. var done = false;
  7818. do {
  7819. parent_1 = Object.getPrototypeOf(currentTarget);
  7820. if (!parent_1.getClassName) {
  7821. done = true;
  7822. break;
  7823. }
  7824. if (parent_1.getClassName() !== currentKey) {
  7825. break;
  7826. }
  7827. currentTarget = parent_1;
  7828. } while (parent_1);
  7829. if (done) {
  7830. break;
  7831. }
  7832. currentKey = parent_1.getClassName();
  7833. currentTarget = parent_1;
  7834. }
  7835. return store;
  7836. }
  7837. function generateSerializableMember(type, sourceName) {
  7838. return function (target, propertyKey) {
  7839. var classStore = getDirectStore(target);
  7840. if (!classStore[propertyKey]) {
  7841. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7842. }
  7843. };
  7844. }
  7845. function generateExpandMember(setCallback, targetKey) {
  7846. if (targetKey === void 0) { targetKey = null; }
  7847. return function (target, propertyKey) {
  7848. var key = targetKey || ("_" + propertyKey);
  7849. Object.defineProperty(target, propertyKey, {
  7850. get: function () {
  7851. return this[key];
  7852. },
  7853. set: function (value) {
  7854. if (this[key] === value) {
  7855. return;
  7856. }
  7857. this[key] = value;
  7858. target[setCallback].apply(this);
  7859. },
  7860. enumerable: true,
  7861. configurable: true
  7862. });
  7863. };
  7864. }
  7865. function expandToProperty(callback, targetKey) {
  7866. if (targetKey === void 0) { targetKey = null; }
  7867. return generateExpandMember(callback, targetKey);
  7868. }
  7869. BABYLON.expandToProperty = expandToProperty;
  7870. function serialize(sourceName) {
  7871. return generateSerializableMember(0, sourceName); // value member
  7872. }
  7873. BABYLON.serialize = serialize;
  7874. function serializeAsTexture(sourceName) {
  7875. return generateSerializableMember(1, sourceName); // texture member
  7876. }
  7877. BABYLON.serializeAsTexture = serializeAsTexture;
  7878. function serializeAsColor3(sourceName) {
  7879. return generateSerializableMember(2, sourceName); // color3 member
  7880. }
  7881. BABYLON.serializeAsColor3 = serializeAsColor3;
  7882. function serializeAsFresnelParameters(sourceName) {
  7883. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7884. }
  7885. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7886. function serializeAsVector2(sourceName) {
  7887. return generateSerializableMember(4, sourceName); // vector2 member
  7888. }
  7889. BABYLON.serializeAsVector2 = serializeAsVector2;
  7890. function serializeAsVector3(sourceName) {
  7891. return generateSerializableMember(5, sourceName); // vector3 member
  7892. }
  7893. BABYLON.serializeAsVector3 = serializeAsVector3;
  7894. function serializeAsMeshReference(sourceName) {
  7895. return generateSerializableMember(6, sourceName); // mesh reference member
  7896. }
  7897. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7898. function serializeAsColorCurves(sourceName) {
  7899. return generateSerializableMember(7, sourceName); // color curves
  7900. }
  7901. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7902. function serializeAsColor4(sourceName) {
  7903. return generateSerializableMember(8, sourceName); // color 4
  7904. }
  7905. BABYLON.serializeAsColor4 = serializeAsColor4;
  7906. function serializeAsImageProcessingConfiguration(sourceName) {
  7907. return generateSerializableMember(9, sourceName); // image processing
  7908. }
  7909. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7910. function serializeAsQuaternion(sourceName) {
  7911. return generateSerializableMember(10, sourceName); // quaternion member
  7912. }
  7913. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7914. /**
  7915. * Decorator used to define property that can be serialized as reference to a camera
  7916. * @param sourceName defines the name of the property to decorate
  7917. */
  7918. function serializeAsCameraReference(sourceName) {
  7919. return generateSerializableMember(11, sourceName); // camera reference member
  7920. }
  7921. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7922. var SerializationHelper = /** @class */ (function () {
  7923. function SerializationHelper() {
  7924. }
  7925. SerializationHelper.Serialize = function (entity, serializationObject) {
  7926. if (!serializationObject) {
  7927. serializationObject = {};
  7928. }
  7929. // Tags
  7930. if (BABYLON.Tags) {
  7931. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7932. }
  7933. var serializedProperties = getMergedStore(entity);
  7934. // Properties
  7935. for (var property in serializedProperties) {
  7936. var propertyDescriptor = serializedProperties[property];
  7937. var targetPropertyName = propertyDescriptor.sourceName || property;
  7938. var propertyType = propertyDescriptor.type;
  7939. var sourceProperty = entity[property];
  7940. if (sourceProperty !== undefined && sourceProperty !== null) {
  7941. switch (propertyType) {
  7942. case 0: // Value
  7943. serializationObject[targetPropertyName] = sourceProperty;
  7944. break;
  7945. case 1: // Texture
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 2: // Color3
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 3: // FresnelParameters
  7952. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7953. break;
  7954. case 4: // Vector2
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 5: // Vector3
  7958. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7959. break;
  7960. case 6: // Mesh reference
  7961. serializationObject[targetPropertyName] = sourceProperty.id;
  7962. break;
  7963. case 7: // Color Curves
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 8: // Color 4
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 9: // Image Processing
  7970. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7971. break;
  7972. case 10: // Quaternion
  7973. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7974. break;
  7975. case 11: // Camera reference
  7976. serializationObject[targetPropertyName] = sourceProperty.id;
  7977. break;
  7978. }
  7979. }
  7980. }
  7981. return serializationObject;
  7982. };
  7983. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7984. if (rootUrl === void 0) { rootUrl = null; }
  7985. var destination = creationFunction();
  7986. if (!rootUrl) {
  7987. rootUrl = "";
  7988. }
  7989. // Tags
  7990. if (BABYLON.Tags) {
  7991. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7992. }
  7993. var classStore = getMergedStore(destination);
  7994. // Properties
  7995. for (var property in classStore) {
  7996. var propertyDescriptor = classStore[property];
  7997. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7998. var propertyType = propertyDescriptor.type;
  7999. if (sourceProperty !== undefined && sourceProperty !== null) {
  8000. var dest = destination;
  8001. switch (propertyType) {
  8002. case 0: // Value
  8003. dest[property] = sourceProperty;
  8004. break;
  8005. case 1: // Texture
  8006. if (scene) {
  8007. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8008. }
  8009. break;
  8010. case 2: // Color3
  8011. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8012. break;
  8013. case 3: // FresnelParameters
  8014. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8015. break;
  8016. case 4: // Vector2
  8017. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8018. break;
  8019. case 5: // Vector3
  8020. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8021. break;
  8022. case 6: // Mesh reference
  8023. if (scene) {
  8024. dest[property] = scene.getLastMeshByID(sourceProperty);
  8025. }
  8026. break;
  8027. case 7: // Color Curves
  8028. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8029. break;
  8030. case 8: // Color 4
  8031. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8032. break;
  8033. case 9: // Image Processing
  8034. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8035. break;
  8036. case 10: // Quaternion
  8037. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8038. break;
  8039. case 11: // Camera reference
  8040. if (scene) {
  8041. dest[property] = scene.getCameraByID(sourceProperty);
  8042. }
  8043. break;
  8044. }
  8045. }
  8046. }
  8047. return destination;
  8048. };
  8049. SerializationHelper.Clone = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, false);
  8051. };
  8052. SerializationHelper.Instanciate = function (creationFunction, source) {
  8053. return _copySource(creationFunction, source, true);
  8054. };
  8055. return SerializationHelper;
  8056. }());
  8057. BABYLON.SerializationHelper = SerializationHelper;
  8058. })(BABYLON || (BABYLON = {}));
  8059. //# sourceMappingURL=babylon.decorators.js.map
  8060. var BABYLON;
  8061. (function (BABYLON) {
  8062. /**
  8063. * Wrapper class for promise with external resolve and reject.
  8064. */
  8065. var Deferred = /** @class */ (function () {
  8066. /**
  8067. * Constructor for this deferred object.
  8068. */
  8069. function Deferred() {
  8070. var _this = this;
  8071. this.promise = new Promise(function (resolve, reject) {
  8072. _this._resolve = resolve;
  8073. _this._reject = reject;
  8074. });
  8075. }
  8076. Object.defineProperty(Deferred.prototype, "resolve", {
  8077. /**
  8078. * The resolve method of the promise associated with this deferred object.
  8079. */
  8080. get: function () {
  8081. return this._resolve;
  8082. },
  8083. enumerable: true,
  8084. configurable: true
  8085. });
  8086. Object.defineProperty(Deferred.prototype, "reject", {
  8087. /**
  8088. * The reject method of the promise associated with this deferred object.
  8089. */
  8090. get: function () {
  8091. return this._reject;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. return Deferred;
  8097. }());
  8098. BABYLON.Deferred = Deferred;
  8099. })(BABYLON || (BABYLON = {}));
  8100. //# sourceMappingURL=babylon.deferred.js.map
  8101. var BABYLON;
  8102. (function (BABYLON) {
  8103. /**
  8104. * A class serves as a medium between the observable and its observers
  8105. */
  8106. var EventState = /** @class */ (function () {
  8107. /**
  8108. * Create a new EventState
  8109. * @param mask defines the mask associated with this state
  8110. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8111. * @param target defines the original target of the state
  8112. * @param currentTarget defines the current target of the state
  8113. */
  8114. function EventState(mask, skipNextObservers, target, currentTarget) {
  8115. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8116. this.initalize(mask, skipNextObservers, target, currentTarget);
  8117. }
  8118. /**
  8119. * Initialize the current event state
  8120. * @param mask defines the mask associated with this state
  8121. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8122. * @param target defines the original target of the state
  8123. * @param currentTarget defines the current target of the state
  8124. * @returns the current event state
  8125. */
  8126. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8127. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8128. this.mask = mask;
  8129. this.skipNextObservers = skipNextObservers;
  8130. this.target = target;
  8131. this.currentTarget = currentTarget;
  8132. return this;
  8133. };
  8134. return EventState;
  8135. }());
  8136. BABYLON.EventState = EventState;
  8137. /**
  8138. * Represent an Observer registered to a given Observable object.
  8139. */
  8140. var Observer = /** @class */ (function () {
  8141. /**
  8142. * Creates a new observer
  8143. * @param callback defines the callback to call when the observer is notified
  8144. * @param mask defines the mask of the observer (used to filter notifications)
  8145. * @param scope defines the current scope used to restore the JS context
  8146. */
  8147. function Observer(
  8148. /**
  8149. * Defines the callback to call when the observer is notified
  8150. */
  8151. callback,
  8152. /**
  8153. * Defines the mask of the observer (used to filter notifications)
  8154. */
  8155. mask,
  8156. /**
  8157. * Defines the current scope used to restore the JS context
  8158. */
  8159. scope) {
  8160. if (scope === void 0) { scope = null; }
  8161. this.callback = callback;
  8162. this.mask = mask;
  8163. this.scope = scope;
  8164. /** @hidden */
  8165. this._willBeUnregistered = false;
  8166. /**
  8167. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8168. */
  8169. this.unregisterOnNextCall = false;
  8170. }
  8171. return Observer;
  8172. }());
  8173. BABYLON.Observer = Observer;
  8174. /**
  8175. * Represent a list of observers registered to multiple Observables object.
  8176. */
  8177. var MultiObserver = /** @class */ (function () {
  8178. function MultiObserver() {
  8179. }
  8180. /**
  8181. * Release associated resources
  8182. */
  8183. MultiObserver.prototype.dispose = function () {
  8184. if (this._observers && this._observables) {
  8185. for (var index = 0; index < this._observers.length; index++) {
  8186. this._observables[index].remove(this._observers[index]);
  8187. }
  8188. }
  8189. this._observers = null;
  8190. this._observables = null;
  8191. };
  8192. /**
  8193. * Raise a callback when one of the observable will notify
  8194. * @param observables defines a list of observables to watch
  8195. * @param callback defines the callback to call on notification
  8196. * @param mask defines the mask used to filter notifications
  8197. * @param scope defines the current scope used to restore the JS context
  8198. * @returns the new MultiObserver
  8199. */
  8200. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8201. if (mask === void 0) { mask = -1; }
  8202. if (scope === void 0) { scope = null; }
  8203. var result = new MultiObserver();
  8204. result._observers = new Array();
  8205. result._observables = observables;
  8206. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8207. var observable = observables_1[_i];
  8208. var observer = observable.add(callback, mask, false, scope);
  8209. if (observer) {
  8210. result._observers.push(observer);
  8211. }
  8212. }
  8213. return result;
  8214. };
  8215. return MultiObserver;
  8216. }());
  8217. BABYLON.MultiObserver = MultiObserver;
  8218. /**
  8219. * The Observable class is a simple implementation of the Observable pattern.
  8220. *
  8221. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8222. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8223. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8224. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8225. */
  8226. var Observable = /** @class */ (function () {
  8227. /**
  8228. * Creates a new observable
  8229. * @param onObserverAdded defines a callback to call when a new observer is added
  8230. */
  8231. function Observable(onObserverAdded) {
  8232. this._observers = new Array();
  8233. this._eventState = new EventState(0);
  8234. if (onObserverAdded) {
  8235. this._onObserverAdded = onObserverAdded;
  8236. }
  8237. }
  8238. /**
  8239. * Create a new Observer with the specified callback
  8240. * @param callback the callback that will be executed for that Observer
  8241. * @param mask the mask used to filter observers
  8242. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8243. * @param scope optional scope for the callback to be called from
  8244. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8245. * @returns the new observer created for the callback
  8246. */
  8247. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8248. if (mask === void 0) { mask = -1; }
  8249. if (insertFirst === void 0) { insertFirst = false; }
  8250. if (scope === void 0) { scope = null; }
  8251. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8252. if (!callback) {
  8253. return null;
  8254. }
  8255. var observer = new Observer(callback, mask, scope);
  8256. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8257. if (insertFirst) {
  8258. this._observers.unshift(observer);
  8259. }
  8260. else {
  8261. this._observers.push(observer);
  8262. }
  8263. if (this._onObserverAdded) {
  8264. this._onObserverAdded(observer);
  8265. }
  8266. return observer;
  8267. };
  8268. /**
  8269. * Create a new Observer with the specified callback and unregisters after the next notification
  8270. * @param callback the callback that will be executed for that Observer
  8271. * @returns the new observer created for the callback
  8272. */
  8273. Observable.prototype.addOnce = function (callback) {
  8274. return this.add(callback, undefined, undefined, undefined, true);
  8275. };
  8276. /**
  8277. * Remove an Observer from the Observable object
  8278. * @param observer the instance of the Observer to remove
  8279. * @returns false if it doesn't belong to this Observable
  8280. */
  8281. Observable.prototype.remove = function (observer) {
  8282. if (!observer) {
  8283. return false;
  8284. }
  8285. var index = this._observers.indexOf(observer);
  8286. if (index !== -1) {
  8287. this._deferUnregister(observer);
  8288. return true;
  8289. }
  8290. return false;
  8291. };
  8292. /**
  8293. * Remove a callback from the Observable object
  8294. * @param callback the callback to remove
  8295. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8296. * @returns false if it doesn't belong to this Observable
  8297. */
  8298. Observable.prototype.removeCallback = function (callback, scope) {
  8299. for (var index = 0; index < this._observers.length; index++) {
  8300. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8301. this._deferUnregister(this._observers[index]);
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. };
  8307. Observable.prototype._deferUnregister = function (observer) {
  8308. var _this = this;
  8309. observer.unregisterOnNextCall = false;
  8310. observer._willBeUnregistered = true;
  8311. BABYLON.Tools.SetImmediate(function () {
  8312. _this._remove(observer);
  8313. });
  8314. };
  8315. // This should only be called when not iterating over _observers to avoid callback skipping.
  8316. // Removes an observer from the _observer Array.
  8317. Observable.prototype._remove = function (observer) {
  8318. if (!observer) {
  8319. return false;
  8320. }
  8321. var index = this._observers.indexOf(observer);
  8322. if (index !== -1) {
  8323. this._observers.splice(index, 1);
  8324. return true;
  8325. }
  8326. return false;
  8327. };
  8328. /**
  8329. * Notify all Observers by calling their respective callback with the given data
  8330. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8331. * @param eventData defines the data to send to all observers
  8332. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8333. * @param target defines the original target of the state
  8334. * @param currentTarget defines the current target of the state
  8335. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8336. */
  8337. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (!this._observers.length) {
  8340. return true;
  8341. }
  8342. var state = this._eventState;
  8343. state.mask = mask;
  8344. state.target = target;
  8345. state.currentTarget = currentTarget;
  8346. state.skipNextObservers = false;
  8347. state.lastReturnValue = eventData;
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs._willBeUnregistered) {
  8351. continue;
  8352. }
  8353. if (obs.mask & mask) {
  8354. if (obs.scope) {
  8355. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8356. }
  8357. else {
  8358. state.lastReturnValue = obs.callback(eventData, state);
  8359. }
  8360. if (obs.unregisterOnNextCall) {
  8361. this._deferUnregister(obs);
  8362. }
  8363. }
  8364. if (state.skipNextObservers) {
  8365. return false;
  8366. }
  8367. }
  8368. return true;
  8369. };
  8370. /**
  8371. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8372. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8373. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8374. * and it is crucial that all callbacks will be executed.
  8375. * The order of the callbacks is kept, callbacks are not executed parallel.
  8376. *
  8377. * @param eventData The data to be sent to each callback
  8378. * @param mask is used to filter observers defaults to -1
  8379. * @param target defines the callback target (see EventState)
  8380. * @param currentTarget defines he current object in the bubbling phase
  8381. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8382. */
  8383. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8384. var _this = this;
  8385. if (mask === void 0) { mask = -1; }
  8386. // create an empty promise
  8387. var p = Promise.resolve(eventData);
  8388. // no observers? return this promise.
  8389. if (!this._observers.length) {
  8390. return p;
  8391. }
  8392. var state = this._eventState;
  8393. state.mask = mask;
  8394. state.target = target;
  8395. state.currentTarget = currentTarget;
  8396. state.skipNextObservers = false;
  8397. // execute one callback after another (not using Promise.all, the order is important)
  8398. this._observers.forEach(function (obs) {
  8399. if (state.skipNextObservers) {
  8400. return;
  8401. }
  8402. if (obs._willBeUnregistered) {
  8403. return;
  8404. }
  8405. if (obs.mask & mask) {
  8406. if (obs.scope) {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback.apply(obs.scope, [eventData, state]);
  8410. });
  8411. }
  8412. else {
  8413. p = p.then(function (lastReturnedValue) {
  8414. state.lastReturnValue = lastReturnedValue;
  8415. return obs.callback(eventData, state);
  8416. });
  8417. }
  8418. if (obs.unregisterOnNextCall) {
  8419. _this._deferUnregister(obs);
  8420. }
  8421. }
  8422. });
  8423. // return the eventData
  8424. return p.then(function () { return eventData; });
  8425. };
  8426. /**
  8427. * Notify a specific observer
  8428. * @param observer defines the observer to notify
  8429. * @param eventData defines the data to be sent to each callback
  8430. * @param mask is used to filter observers defaults to -1
  8431. */
  8432. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8433. if (mask === void 0) { mask = -1; }
  8434. var state = this._eventState;
  8435. state.mask = mask;
  8436. state.skipNextObservers = false;
  8437. observer.callback(eventData, state);
  8438. };
  8439. /**
  8440. * Gets a boolean indicating if the observable has at least one observer
  8441. * @returns true is the Observable has at least one Observer registered
  8442. */
  8443. Observable.prototype.hasObservers = function () {
  8444. return this._observers.length > 0;
  8445. };
  8446. /**
  8447. * Clear the list of observers
  8448. */
  8449. Observable.prototype.clear = function () {
  8450. this._observers = new Array();
  8451. this._onObserverAdded = null;
  8452. };
  8453. /**
  8454. * Clone the current observable
  8455. * @returns a new observable
  8456. */
  8457. Observable.prototype.clone = function () {
  8458. var result = new Observable();
  8459. result._observers = this._observers.slice(0);
  8460. return result;
  8461. };
  8462. /**
  8463. * Does this observable handles observer registered with a given mask
  8464. * @param mask defines the mask to be tested
  8465. * @return whether or not one observer registered with the given mask is handeled
  8466. **/
  8467. Observable.prototype.hasSpecificMask = function (mask) {
  8468. if (mask === void 0) { mask = -1; }
  8469. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8470. var obs = _a[_i];
  8471. if (obs.mask & mask || obs.mask === mask) {
  8472. return true;
  8473. }
  8474. }
  8475. return false;
  8476. };
  8477. return Observable;
  8478. }());
  8479. BABYLON.Observable = Observable;
  8480. })(BABYLON || (BABYLON = {}));
  8481. //# sourceMappingURL=babylon.observable.js.map
  8482. var BABYLON;
  8483. (function (BABYLON) {
  8484. var SmartArray = /** @class */ (function () {
  8485. function SmartArray(capacity) {
  8486. this.length = 0;
  8487. this.data = new Array(capacity);
  8488. this._id = SmartArray._GlobalId++;
  8489. }
  8490. SmartArray.prototype.push = function (value) {
  8491. this.data[this.length++] = value;
  8492. if (this.length > this.data.length) {
  8493. this.data.length *= 2;
  8494. }
  8495. };
  8496. SmartArray.prototype.forEach = function (func) {
  8497. for (var index = 0; index < this.length; index++) {
  8498. func(this.data[index]);
  8499. }
  8500. };
  8501. SmartArray.prototype.sort = function (compareFn) {
  8502. this.data.sort(compareFn);
  8503. };
  8504. SmartArray.prototype.reset = function () {
  8505. this.length = 0;
  8506. };
  8507. SmartArray.prototype.dispose = function () {
  8508. this.reset();
  8509. if (this.data) {
  8510. this.data.length = 0;
  8511. this.data = [];
  8512. }
  8513. };
  8514. SmartArray.prototype.concat = function (array) {
  8515. if (array.length === 0) {
  8516. return;
  8517. }
  8518. if (this.length + array.length > this.data.length) {
  8519. this.data.length = (this.length + array.length) * 2;
  8520. }
  8521. for (var index = 0; index < array.length; index++) {
  8522. this.data[this.length++] = (array.data || array)[index];
  8523. }
  8524. };
  8525. SmartArray.prototype.indexOf = function (value) {
  8526. var position = this.data.indexOf(value);
  8527. if (position >= this.length) {
  8528. return -1;
  8529. }
  8530. return position;
  8531. };
  8532. SmartArray.prototype.contains = function (value) {
  8533. return this.data.indexOf(value) !== -1;
  8534. };
  8535. // Statics
  8536. SmartArray._GlobalId = 0;
  8537. return SmartArray;
  8538. }());
  8539. BABYLON.SmartArray = SmartArray;
  8540. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8541. __extends(SmartArrayNoDuplicate, _super);
  8542. function SmartArrayNoDuplicate() {
  8543. var _this = _super !== null && _super.apply(this, arguments) || this;
  8544. _this._duplicateId = 0;
  8545. return _this;
  8546. }
  8547. SmartArrayNoDuplicate.prototype.push = function (value) {
  8548. _super.prototype.push.call(this, value);
  8549. if (!value.__smartArrayFlags) {
  8550. value.__smartArrayFlags = {};
  8551. }
  8552. value.__smartArrayFlags[this._id] = this._duplicateId;
  8553. };
  8554. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8555. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8556. return false;
  8557. }
  8558. this.push(value);
  8559. return true;
  8560. };
  8561. SmartArrayNoDuplicate.prototype.reset = function () {
  8562. _super.prototype.reset.call(this);
  8563. this._duplicateId++;
  8564. };
  8565. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8566. if (array.length === 0) {
  8567. return;
  8568. }
  8569. if (this.length + array.length > this.data.length) {
  8570. this.data.length = (this.length + array.length) * 2;
  8571. }
  8572. for (var index = 0; index < array.length; index++) {
  8573. var item = (array.data || array)[index];
  8574. this.pushNoDuplicate(item);
  8575. }
  8576. };
  8577. return SmartArrayNoDuplicate;
  8578. }(SmartArray));
  8579. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8580. })(BABYLON || (BABYLON = {}));
  8581. //# sourceMappingURL=babylon.smartArray.js.map
  8582. var BABYLON;
  8583. (function (BABYLON) {
  8584. /** Class used to store color gradient */
  8585. var ColorGradient = /** @class */ (function () {
  8586. function ColorGradient() {
  8587. }
  8588. /**
  8589. * Will get a color picked randomly between color1 and color2.
  8590. * If color2 is undefined then color1 will be used
  8591. * @param result defines the target Color4 to store the result in
  8592. */
  8593. ColorGradient.prototype.getColorToRef = function (result) {
  8594. if (!this.color2) {
  8595. result.copyFrom(this.color1);
  8596. return;
  8597. }
  8598. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8599. };
  8600. return ColorGradient;
  8601. }());
  8602. BABYLON.ColorGradient = ColorGradient;
  8603. /** Class used to store factor gradient */
  8604. var FactorGradient = /** @class */ (function () {
  8605. function FactorGradient() {
  8606. }
  8607. /**
  8608. * Will get a number picked randomly between factor1 and factor2.
  8609. * If factor2 is undefined then factor1 will be used
  8610. * @returns the picked number
  8611. */
  8612. FactorGradient.prototype.getFactor = function () {
  8613. if (this.factor2 === undefined) {
  8614. return this.factor1;
  8615. }
  8616. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8617. };
  8618. return FactorGradient;
  8619. }());
  8620. BABYLON.FactorGradient = FactorGradient;
  8621. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8622. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8623. var LoadFileError = /** @class */ (function (_super) {
  8624. __extends(LoadFileError, _super);
  8625. function LoadFileError(message, request) {
  8626. var _this = _super.call(this, message) || this;
  8627. _this.request = request;
  8628. _this.name = "LoadFileError";
  8629. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8630. return _this;
  8631. }
  8632. // Polyfill for Object.setPrototypeOf if necessary.
  8633. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8634. return LoadFileError;
  8635. }(Error));
  8636. BABYLON.LoadFileError = LoadFileError;
  8637. var RetryStrategy = /** @class */ (function () {
  8638. function RetryStrategy() {
  8639. }
  8640. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8641. if (maxRetries === void 0) { maxRetries = 3; }
  8642. if (baseInterval === void 0) { baseInterval = 500; }
  8643. return function (url, request, retryIndex) {
  8644. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8645. return -1;
  8646. }
  8647. return Math.pow(2, retryIndex) * baseInterval;
  8648. };
  8649. };
  8650. return RetryStrategy;
  8651. }());
  8652. BABYLON.RetryStrategy = RetryStrategy;
  8653. // Screenshots
  8654. var screenshotCanvas;
  8655. var cloneValue = function (source, destinationObject) {
  8656. if (!source)
  8657. return null;
  8658. if (source instanceof BABYLON.Mesh) {
  8659. return null;
  8660. }
  8661. if (source instanceof BABYLON.SubMesh) {
  8662. return source.clone(destinationObject);
  8663. }
  8664. else if (source.clone) {
  8665. return source.clone();
  8666. }
  8667. return null;
  8668. };
  8669. var Tools = /** @class */ (function () {
  8670. function Tools() {
  8671. }
  8672. /**
  8673. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8674. * @param u defines the coordinate on X axis
  8675. * @param v defines the coordinate on Y axis
  8676. * @param width defines the width of the source data
  8677. * @param height defines the height of the source data
  8678. * @param pixels defines the source byte array
  8679. * @param color defines the output color
  8680. */
  8681. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8682. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8683. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8684. var position = (wrappedU + wrappedV * width) * 4;
  8685. color.r = pixels[position] / 255;
  8686. color.g = pixels[position + 1] / 255;
  8687. color.b = pixels[position + 2] / 255;
  8688. color.a = pixels[position + 3] / 255;
  8689. };
  8690. /**
  8691. * Interpolates between a and b via alpha
  8692. * @param a The lower value (returned when alpha = 0)
  8693. * @param b The upper value (returned when alpha = 1)
  8694. * @param alpha The interpolation-factor
  8695. * @return The mixed value
  8696. */
  8697. Tools.Mix = function (a, b, alpha) {
  8698. return a * (1 - alpha) + b * alpha;
  8699. };
  8700. Tools.Instantiate = function (className) {
  8701. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8702. return Tools.RegisteredExternalClasses[className];
  8703. }
  8704. var arr = className.split(".");
  8705. var fn = (window || this);
  8706. for (var i = 0, len = arr.length; i < len; i++) {
  8707. fn = fn[arr[i]];
  8708. }
  8709. if (typeof fn !== "function") {
  8710. return null;
  8711. }
  8712. return fn;
  8713. };
  8714. /**
  8715. * Provides a slice function that will work even on IE
  8716. * @param data defines the array to slice
  8717. * @param start defines the start of the data (optional)
  8718. * @param end defines the end of the data (optional)
  8719. * @returns the new sliced array
  8720. */
  8721. Tools.Slice = function (data, start, end) {
  8722. if (data.slice) {
  8723. return data.slice(start, end);
  8724. }
  8725. return Array.prototype.slice.call(data, start, end);
  8726. };
  8727. Tools.SetImmediate = function (action) {
  8728. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8729. window.setImmediate(action);
  8730. }
  8731. else {
  8732. setTimeout(action, 1);
  8733. }
  8734. };
  8735. Tools.IsExponentOfTwo = function (value) {
  8736. var count = 1;
  8737. do {
  8738. count *= 2;
  8739. } while (count < value);
  8740. return count === value;
  8741. };
  8742. /**
  8743. * Returns the nearest 32-bit single precision float representation of a Number
  8744. * @param value A Number. If the parameter is of a different type, it will get converted
  8745. * to a number or to NaN if it cannot be converted
  8746. * @returns number
  8747. */
  8748. Tools.FloatRound = function (value) {
  8749. if (Math.fround) {
  8750. return Math.fround(value);
  8751. }
  8752. return (Tools._tmpFloatArray[0] = value);
  8753. };
  8754. /**
  8755. * Find the next highest power of two.
  8756. * @param x Number to start search from.
  8757. * @return Next highest power of two.
  8758. */
  8759. Tools.CeilingPOT = function (x) {
  8760. x--;
  8761. x |= x >> 1;
  8762. x |= x >> 2;
  8763. x |= x >> 4;
  8764. x |= x >> 8;
  8765. x |= x >> 16;
  8766. x++;
  8767. return x;
  8768. };
  8769. /**
  8770. * Find the next lowest power of two.
  8771. * @param x Number to start search from.
  8772. * @return Next lowest power of two.
  8773. */
  8774. Tools.FloorPOT = function (x) {
  8775. x = x | (x >> 1);
  8776. x = x | (x >> 2);
  8777. x = x | (x >> 4);
  8778. x = x | (x >> 8);
  8779. x = x | (x >> 16);
  8780. return x - (x >> 1);
  8781. };
  8782. /**
  8783. * Find the nearest power of two.
  8784. * @param x Number to start search from.
  8785. * @return Next nearest power of two.
  8786. */
  8787. Tools.NearestPOT = function (x) {
  8788. var c = Tools.CeilingPOT(x);
  8789. var f = Tools.FloorPOT(x);
  8790. return (c - x) > (x - f) ? f : c;
  8791. };
  8792. Tools.GetExponentOfTwo = function (value, max, mode) {
  8793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8794. var pot;
  8795. switch (mode) {
  8796. case BABYLON.Engine.SCALEMODE_FLOOR:
  8797. pot = Tools.FloorPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_NEAREST:
  8800. pot = Tools.NearestPOT(value);
  8801. break;
  8802. case BABYLON.Engine.SCALEMODE_CEILING:
  8803. default:
  8804. pot = Tools.CeilingPOT(value);
  8805. break;
  8806. }
  8807. return Math.min(pot, max);
  8808. };
  8809. Tools.GetFilename = function (path) {
  8810. var index = path.lastIndexOf("/");
  8811. if (index < 0)
  8812. return path;
  8813. return path.substring(index + 1);
  8814. };
  8815. /**
  8816. * Extracts the "folder" part of a path (everything before the filename).
  8817. * @param uri The URI to extract the info from
  8818. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8819. * @returns The "folder" part of the path
  8820. */
  8821. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8822. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8823. var index = uri.lastIndexOf("/");
  8824. if (index < 0) {
  8825. if (returnUnchangedIfNoSlash) {
  8826. return uri;
  8827. }
  8828. return "";
  8829. }
  8830. return uri.substring(0, index + 1);
  8831. };
  8832. Tools.GetDOMTextContent = function (element) {
  8833. var result = "";
  8834. var child = element.firstChild;
  8835. while (child) {
  8836. if (child.nodeType === 3) {
  8837. result += child.textContent;
  8838. }
  8839. child = child.nextSibling;
  8840. }
  8841. return result;
  8842. };
  8843. Tools.ToDegrees = function (angle) {
  8844. return angle * 180 / Math.PI;
  8845. };
  8846. Tools.ToRadians = function (angle) {
  8847. return angle * Math.PI / 180;
  8848. };
  8849. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8850. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8851. var output = "";
  8852. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8853. var i = 0;
  8854. var bytes = new Uint8Array(buffer);
  8855. while (i < bytes.length) {
  8856. chr1 = bytes[i++];
  8857. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8858. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8859. enc1 = chr1 >> 2;
  8860. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8861. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8862. enc4 = chr3 & 63;
  8863. if (isNaN(chr2)) {
  8864. enc3 = enc4 = 64;
  8865. }
  8866. else if (isNaN(chr3)) {
  8867. enc4 = 64;
  8868. }
  8869. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8870. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8871. }
  8872. return "data:image/png;base64," + output;
  8873. };
  8874. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8875. if (bias === void 0) { bias = null; }
  8876. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8877. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8878. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8879. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8880. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8881. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8882. }
  8883. if (bias) {
  8884. minimum.x -= minimum.x * bias.x + bias.y;
  8885. minimum.y -= minimum.y * bias.x + bias.y;
  8886. minimum.z -= minimum.z * bias.x + bias.y;
  8887. maximum.x += maximum.x * bias.x + bias.y;
  8888. maximum.y += maximum.y * bias.x + bias.y;
  8889. maximum.z += maximum.z * bias.x + bias.y;
  8890. }
  8891. return {
  8892. minimum: minimum,
  8893. maximum: maximum
  8894. };
  8895. };
  8896. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8897. if (bias === void 0) { bias = null; }
  8898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8900. if (!stride) {
  8901. stride = 3;
  8902. }
  8903. for (var index = start; index < start + count; index++) {
  8904. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8907. }
  8908. if (bias) {
  8909. minimum.x -= minimum.x * bias.x + bias.y;
  8910. minimum.y -= minimum.y * bias.x + bias.y;
  8911. minimum.z -= minimum.z * bias.x + bias.y;
  8912. maximum.x += maximum.x * bias.x + bias.y;
  8913. maximum.y += maximum.y * bias.x + bias.y;
  8914. maximum.z += maximum.z * bias.x + bias.y;
  8915. }
  8916. return {
  8917. minimum: minimum,
  8918. maximum: maximum
  8919. };
  8920. };
  8921. Tools.Vector2ArrayFeeder = function (array) {
  8922. return function (index) {
  8923. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8924. var length = isFloatArray ? array.length / 2 : array.length;
  8925. if (index >= length) {
  8926. return null;
  8927. }
  8928. if (isFloatArray) {
  8929. var fa = array;
  8930. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8931. }
  8932. var a = array;
  8933. return a[index];
  8934. };
  8935. };
  8936. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8937. if (bias === void 0) { bias = null; }
  8938. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8939. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8940. var i = 0;
  8941. var cur = feeder(i++);
  8942. while (cur) {
  8943. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8944. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8945. cur = feeder(i++);
  8946. }
  8947. if (bias) {
  8948. minimum.x -= minimum.x * bias.x + bias.y;
  8949. minimum.y -= minimum.y * bias.x + bias.y;
  8950. maximum.x += maximum.x * bias.x + bias.y;
  8951. maximum.y += maximum.y * bias.x + bias.y;
  8952. }
  8953. return {
  8954. minimum: minimum,
  8955. maximum: maximum
  8956. };
  8957. };
  8958. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8959. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8960. return null;
  8961. return Array.isArray(obj) ? obj : [obj];
  8962. };
  8963. // Misc.
  8964. Tools.GetPointerPrefix = function () {
  8965. var eventPrefix = "pointer";
  8966. // Check if pointer events are supported
  8967. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8968. eventPrefix = "mouse";
  8969. }
  8970. return eventPrefix;
  8971. };
  8972. /**
  8973. * @param func - the function to be called
  8974. * @param requester - the object that will request the next frame. Falls back to window.
  8975. */
  8976. Tools.QueueNewFrame = function (func, requester) {
  8977. if (!Tools.IsWindowObjectExist()) {
  8978. return setTimeout(func, 16);
  8979. }
  8980. if (!requester) {
  8981. requester = window;
  8982. }
  8983. if (requester.requestAnimationFrame) {
  8984. return requester.requestAnimationFrame(func);
  8985. }
  8986. else if (requester.msRequestAnimationFrame) {
  8987. return requester.msRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.webkitRequestAnimationFrame) {
  8990. return requester.webkitRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.mozRequestAnimationFrame) {
  8993. return requester.mozRequestAnimationFrame(func);
  8994. }
  8995. else if (requester.oRequestAnimationFrame) {
  8996. return requester.oRequestAnimationFrame(func);
  8997. }
  8998. else {
  8999. return window.setTimeout(func, 16);
  9000. }
  9001. };
  9002. Tools.RequestFullscreen = function (element) {
  9003. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9004. if (!requestFunction)
  9005. return;
  9006. requestFunction.call(element);
  9007. };
  9008. Tools.ExitFullscreen = function () {
  9009. if (document.exitFullscreen) {
  9010. document.exitFullscreen();
  9011. }
  9012. else if (document.mozCancelFullScreen) {
  9013. document.mozCancelFullScreen();
  9014. }
  9015. else if (document.webkitCancelFullScreen) {
  9016. document.webkitCancelFullScreen();
  9017. }
  9018. else if (document.msCancelFullScreen) {
  9019. document.msCancelFullScreen();
  9020. }
  9021. };
  9022. Tools.SetCorsBehavior = function (url, element) {
  9023. if (url && url.indexOf("data:") === 0) {
  9024. return;
  9025. }
  9026. if (Tools.CorsBehavior) {
  9027. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9028. element.crossOrigin = Tools.CorsBehavior;
  9029. }
  9030. else {
  9031. var result = Tools.CorsBehavior(url);
  9032. if (result) {
  9033. element.crossOrigin = result;
  9034. }
  9035. }
  9036. }
  9037. };
  9038. // External files
  9039. Tools.CleanUrl = function (url) {
  9040. url = url.replace(/#/mg, "%23");
  9041. return url;
  9042. };
  9043. /**
  9044. * Loads an image as an HTMLImageElement.
  9045. * @param input url string, ArrayBuffer, or Blob to load
  9046. * @param onLoad callback called when the image successfully loads
  9047. * @param onError callback called when the image fails to load
  9048. * @param database database for caching
  9049. * @returns the HTMLImageElement of the loaded image
  9050. */
  9051. Tools.LoadImage = function (input, onLoad, onError, database) {
  9052. var url;
  9053. var usingObjectURL = false;
  9054. if (input instanceof ArrayBuffer) {
  9055. url = URL.createObjectURL(new Blob([input]));
  9056. usingObjectURL = true;
  9057. }
  9058. else if (input instanceof Blob) {
  9059. url = URL.createObjectURL(input);
  9060. usingObjectURL = true;
  9061. }
  9062. else {
  9063. url = Tools.CleanUrl(input);
  9064. url = Tools.PreprocessUrl(input);
  9065. }
  9066. var img = new Image();
  9067. Tools.SetCorsBehavior(url, img);
  9068. var loadHandler = function () {
  9069. if (usingObjectURL && img.src) {
  9070. URL.revokeObjectURL(img.src);
  9071. }
  9072. img.removeEventListener("load", loadHandler);
  9073. img.removeEventListener("error", errorHandler);
  9074. onLoad(img);
  9075. };
  9076. var errorHandler = function (err) {
  9077. if (usingObjectURL && img.src) {
  9078. URL.revokeObjectURL(img.src);
  9079. }
  9080. img.removeEventListener("load", loadHandler);
  9081. img.removeEventListener("error", errorHandler);
  9082. Tools.Error("Error while trying to load image: " + input);
  9083. if (onError) {
  9084. onError("Error while trying to load image: " + input, err);
  9085. }
  9086. };
  9087. img.addEventListener("load", loadHandler);
  9088. img.addEventListener("error", errorHandler);
  9089. var noIndexedDB = function () {
  9090. img.src = url;
  9091. };
  9092. var loadFromIndexedDB = function () {
  9093. if (database) {
  9094. database.loadImageFromDB(url, img);
  9095. }
  9096. };
  9097. //ANY database to do!
  9098. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9099. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9100. }
  9101. else {
  9102. if (url.indexOf("file:") !== -1) {
  9103. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9104. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9105. try {
  9106. var blobURL;
  9107. try {
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. catch (ex) {
  9111. // Chrome doesn't support oneTimeOnly parameter
  9112. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9113. }
  9114. img.src = blobURL;
  9115. usingObjectURL = true;
  9116. }
  9117. catch (e) {
  9118. img.src = "";
  9119. }
  9120. return img;
  9121. }
  9122. }
  9123. noIndexedDB();
  9124. }
  9125. return img;
  9126. };
  9127. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9128. url = Tools.CleanUrl(url);
  9129. url = Tools.PreprocessUrl(url);
  9130. // If file and file input are set
  9131. if (url.indexOf("file:") !== -1) {
  9132. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9133. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9134. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9135. }
  9136. }
  9137. var loadUrl = Tools.BaseUrl + url;
  9138. var aborted = false;
  9139. var fileRequest = {
  9140. onCompleteObservable: new BABYLON.Observable(),
  9141. abort: function () { return aborted = true; },
  9142. };
  9143. var requestFile = function () {
  9144. var request = new XMLHttpRequest();
  9145. var retryHandle = null;
  9146. fileRequest.abort = function () {
  9147. aborted = true;
  9148. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9149. request.abort();
  9150. }
  9151. if (retryHandle !== null) {
  9152. clearTimeout(retryHandle);
  9153. retryHandle = null;
  9154. }
  9155. };
  9156. var retryLoop = function (retryIndex) {
  9157. request.open('GET', loadUrl, true);
  9158. if (useArrayBuffer) {
  9159. request.responseType = "arraybuffer";
  9160. }
  9161. if (onProgress) {
  9162. request.addEventListener("progress", onProgress);
  9163. }
  9164. var onLoadEnd = function () {
  9165. request.removeEventListener("loadend", onLoadEnd);
  9166. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9167. fileRequest.onCompleteObservable.clear();
  9168. };
  9169. request.addEventListener("loadend", onLoadEnd);
  9170. var onReadyStateChange = function () {
  9171. if (aborted) {
  9172. return;
  9173. }
  9174. // In case of undefined state in some browsers.
  9175. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9176. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9177. request.removeEventListener("readystatechange", onReadyStateChange);
  9178. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9179. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9180. return;
  9181. }
  9182. var retryStrategy = Tools.DefaultRetryStrategy;
  9183. if (retryStrategy) {
  9184. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9185. if (waitTime !== -1) {
  9186. // Prevent the request from completing for retry.
  9187. request.removeEventListener("loadend", onLoadEnd);
  9188. request = new XMLHttpRequest();
  9189. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9190. return;
  9191. }
  9192. }
  9193. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9194. if (onError) {
  9195. onError(request, e);
  9196. }
  9197. else {
  9198. throw e;
  9199. }
  9200. }
  9201. };
  9202. request.addEventListener("readystatechange", onReadyStateChange);
  9203. request.send();
  9204. };
  9205. retryLoop(0);
  9206. };
  9207. // Caching all files
  9208. if (database && database.enableSceneOffline) {
  9209. var noIndexedDB_1 = function (request) {
  9210. if (request && request.status > 400) {
  9211. if (onError) {
  9212. onError(request);
  9213. }
  9214. }
  9215. else {
  9216. if (!aborted) {
  9217. requestFile();
  9218. }
  9219. }
  9220. };
  9221. var loadFromIndexedDB = function () {
  9222. // TODO: database needs to support aborting and should return a IFileRequest
  9223. if (aborted) {
  9224. return;
  9225. }
  9226. if (database) {
  9227. database.loadFileFromDB(url, function (data) {
  9228. if (!aborted) {
  9229. onSuccess(data);
  9230. }
  9231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9232. }, onProgress ? function (event) {
  9233. if (!aborted) {
  9234. onProgress(event);
  9235. }
  9236. } : undefined, noIndexedDB_1, useArrayBuffer);
  9237. }
  9238. };
  9239. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9240. }
  9241. else {
  9242. requestFile();
  9243. }
  9244. return fileRequest;
  9245. };
  9246. /**
  9247. * Load a script (identified by an url). When the url returns, the
  9248. * content of this file is added into a new script element, attached to the DOM (body element)
  9249. */
  9250. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9251. if (!Tools.IsWindowObjectExist()) {
  9252. return;
  9253. }
  9254. var head = document.getElementsByTagName('head')[0];
  9255. var script = document.createElement('script');
  9256. script.type = 'text/javascript';
  9257. script.src = scriptUrl;
  9258. script.onload = function () {
  9259. if (onSuccess) {
  9260. onSuccess();
  9261. }
  9262. };
  9263. script.onerror = function (e) {
  9264. if (onError) {
  9265. onError("Unable to load script '" + scriptUrl + "'", e);
  9266. }
  9267. };
  9268. head.appendChild(script);
  9269. };
  9270. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9271. var reader = new FileReader();
  9272. var request = {
  9273. onCompleteObservable: new BABYLON.Observable(),
  9274. abort: function () { return reader.abort(); },
  9275. };
  9276. reader.onloadend = function (e) {
  9277. request.onCompleteObservable.notifyObservers(request);
  9278. };
  9279. reader.onload = function (e) {
  9280. //target doesn't have result from ts 1.3
  9281. callback(e.target['result']);
  9282. };
  9283. reader.onprogress = progressCallback;
  9284. reader.readAsDataURL(fileToLoad);
  9285. return request;
  9286. };
  9287. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9288. var reader = new FileReader();
  9289. var request = {
  9290. onCompleteObservable: new BABYLON.Observable(),
  9291. abort: function () { return reader.abort(); },
  9292. };
  9293. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9294. reader.onerror = function (e) {
  9295. Tools.Log("Error while reading file: " + fileToLoad.name);
  9296. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9297. };
  9298. reader.onload = function (e) {
  9299. //target doesn't have result from ts 1.3
  9300. callback(e.target['result']);
  9301. };
  9302. if (progressCallBack) {
  9303. reader.onprogress = progressCallBack;
  9304. }
  9305. if (!useArrayBuffer) {
  9306. // Asynchronous read
  9307. reader.readAsText(fileToLoad);
  9308. }
  9309. else {
  9310. reader.readAsArrayBuffer(fileToLoad);
  9311. }
  9312. return request;
  9313. };
  9314. //returns a downloadable url to a file content.
  9315. Tools.FileAsURL = function (content) {
  9316. var fileBlob = new Blob([content]);
  9317. var url = window.URL || window.webkitURL;
  9318. var link = url.createObjectURL(fileBlob);
  9319. return link;
  9320. };
  9321. // Misc.
  9322. Tools.Format = function (value, decimals) {
  9323. if (decimals === void 0) { decimals = 2; }
  9324. return value.toFixed(decimals);
  9325. };
  9326. Tools.CheckExtends = function (v, min, max) {
  9327. if (v.x < min.x)
  9328. min.x = v.x;
  9329. if (v.y < min.y)
  9330. min.y = v.y;
  9331. if (v.z < min.z)
  9332. min.z = v.z;
  9333. if (v.x > max.x)
  9334. max.x = v.x;
  9335. if (v.y > max.y)
  9336. max.y = v.y;
  9337. if (v.z > max.z)
  9338. max.z = v.z;
  9339. };
  9340. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9341. for (var prop in source) {
  9342. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9343. continue;
  9344. }
  9345. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9346. continue;
  9347. }
  9348. var sourceValue = source[prop];
  9349. var typeOfSourceValue = typeof sourceValue;
  9350. if (typeOfSourceValue === "function") {
  9351. continue;
  9352. }
  9353. try {
  9354. if (typeOfSourceValue === "object") {
  9355. if (sourceValue instanceof Array) {
  9356. destination[prop] = [];
  9357. if (sourceValue.length > 0) {
  9358. if (typeof sourceValue[0] == "object") {
  9359. for (var index = 0; index < sourceValue.length; index++) {
  9360. var clonedValue = cloneValue(sourceValue[index], destination);
  9361. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9362. destination[prop].push(clonedValue);
  9363. }
  9364. }
  9365. }
  9366. else {
  9367. destination[prop] = sourceValue.slice(0);
  9368. }
  9369. }
  9370. }
  9371. else {
  9372. destination[prop] = cloneValue(sourceValue, destination);
  9373. }
  9374. }
  9375. else {
  9376. destination[prop] = sourceValue;
  9377. }
  9378. }
  9379. catch (e) {
  9380. // Just ignore error (it could be because of a read-only property)
  9381. }
  9382. }
  9383. };
  9384. Tools.IsEmpty = function (obj) {
  9385. for (var i in obj) {
  9386. if (obj.hasOwnProperty(i)) {
  9387. return false;
  9388. }
  9389. }
  9390. return true;
  9391. };
  9392. Tools.RegisterTopRootEvents = function (events) {
  9393. for (var index = 0; index < events.length; index++) {
  9394. var event = events[index];
  9395. window.addEventListener(event.name, event.handler, false);
  9396. try {
  9397. if (window.parent) {
  9398. window.parent.addEventListener(event.name, event.handler, false);
  9399. }
  9400. }
  9401. catch (e) {
  9402. // Silently fails...
  9403. }
  9404. }
  9405. };
  9406. Tools.UnregisterTopRootEvents = function (events) {
  9407. for (var index = 0; index < events.length; index++) {
  9408. var event = events[index];
  9409. window.removeEventListener(event.name, event.handler);
  9410. try {
  9411. if (window.parent) {
  9412. window.parent.removeEventListener(event.name, event.handler);
  9413. }
  9414. }
  9415. catch (e) {
  9416. // Silently fails...
  9417. }
  9418. }
  9419. };
  9420. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9421. if (mimeType === void 0) { mimeType = "image/png"; }
  9422. // Read the contents of the framebuffer
  9423. var numberOfChannelsByLine = width * 4;
  9424. var halfHeight = height / 2;
  9425. //Reading datas from WebGL
  9426. var data = engine.readPixels(0, 0, width, height);
  9427. //To flip image on Y axis.
  9428. for (var i = 0; i < halfHeight; i++) {
  9429. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9430. var currentCell = j + i * numberOfChannelsByLine;
  9431. var targetLine = height - i - 1;
  9432. var targetCell = j + targetLine * numberOfChannelsByLine;
  9433. var temp = data[currentCell];
  9434. data[currentCell] = data[targetCell];
  9435. data[targetCell] = temp;
  9436. }
  9437. }
  9438. // Create a 2D canvas to store the result
  9439. if (!screenshotCanvas) {
  9440. screenshotCanvas = document.createElement('canvas');
  9441. }
  9442. screenshotCanvas.width = width;
  9443. screenshotCanvas.height = height;
  9444. var context = screenshotCanvas.getContext('2d');
  9445. if (context) {
  9446. // Copy the pixels to a 2D canvas
  9447. var imageData = context.createImageData(width, height);
  9448. var castData = (imageData.data);
  9449. castData.set(data);
  9450. context.putImageData(imageData, 0, 0);
  9451. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9452. }
  9453. };
  9454. /**
  9455. * Converts the canvas data to blob.
  9456. * This acts as a polyfill for browsers not supporting the to blob function.
  9457. * @param canvas Defines the canvas to extract the data from
  9458. * @param successCallback Defines the callback triggered once the data are available
  9459. * @param mimeType Defines the mime type of the result
  9460. */
  9461. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9462. if (mimeType === void 0) { mimeType = "image/png"; }
  9463. // We need HTMLCanvasElement.toBlob for HD screenshots
  9464. if (!canvas.toBlob) {
  9465. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9466. canvas.toBlob = function (callback, type, quality) {
  9467. var _this = this;
  9468. setTimeout(function () {
  9469. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9470. for (var i = 0; i < len; i++) {
  9471. arr[i] = binStr.charCodeAt(i);
  9472. }
  9473. callback(new Blob([arr]));
  9474. });
  9475. };
  9476. }
  9477. canvas.toBlob(function (blob) {
  9478. successCallback(blob);
  9479. }, mimeType);
  9480. };
  9481. /**
  9482. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9483. * @param successCallback Defines the callback triggered once the data are available
  9484. * @param mimeType Defines the mime type of the result
  9485. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9486. */
  9487. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9488. if (mimeType === void 0) { mimeType = "image/png"; }
  9489. if (successCallback) {
  9490. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9491. successCallback(base64Image);
  9492. }
  9493. else {
  9494. this.ToBlob(screenshotCanvas, function (blob) {
  9495. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9496. if (("download" in document.createElement("a"))) {
  9497. if (!fileName) {
  9498. var date = new Date();
  9499. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9500. fileName = "screenshot_" + stringDate + ".png";
  9501. }
  9502. Tools.Download(blob, fileName);
  9503. }
  9504. else {
  9505. var url = URL.createObjectURL(blob);
  9506. var newWindow = window.open("");
  9507. if (!newWindow)
  9508. return;
  9509. var img = newWindow.document.createElement("img");
  9510. img.onload = function () {
  9511. // no longer need to read the blob so it's revoked
  9512. URL.revokeObjectURL(url);
  9513. };
  9514. img.src = url;
  9515. newWindow.document.body.appendChild(img);
  9516. }
  9517. }, mimeType);
  9518. }
  9519. };
  9520. /**
  9521. * Downloads a blob in the browser
  9522. * @param blob defines the blob to download
  9523. * @param fileName defines the name of the downloaded file
  9524. */
  9525. Tools.Download = function (blob, fileName) {
  9526. if (navigator && navigator.msSaveBlob) {
  9527. navigator.msSaveBlob(blob, fileName);
  9528. return;
  9529. }
  9530. var url = window.URL.createObjectURL(blob);
  9531. var a = document.createElement("a");
  9532. document.body.appendChild(a);
  9533. a.style.display = "none";
  9534. a.href = url;
  9535. a.download = fileName;
  9536. a.addEventListener("click", function () {
  9537. if (a.parentElement) {
  9538. a.parentElement.removeChild(a);
  9539. }
  9540. });
  9541. a.click();
  9542. window.URL.revokeObjectURL(url);
  9543. };
  9544. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9545. if (mimeType === void 0) { mimeType = "image/png"; }
  9546. var width;
  9547. var height;
  9548. // If a precision value is specified
  9549. if (size.precision) {
  9550. width = Math.round(engine.getRenderWidth() * size.precision);
  9551. height = Math.round(width / engine.getAspectRatio(camera));
  9552. }
  9553. else if (size.width && size.height) {
  9554. width = size.width;
  9555. height = size.height;
  9556. }
  9557. //If passing only width, computing height to keep display canvas ratio.
  9558. else if (size.width && !size.height) {
  9559. width = size.width;
  9560. height = Math.round(width / engine.getAspectRatio(camera));
  9561. }
  9562. //If passing only height, computing width to keep display canvas ratio.
  9563. else if (size.height && !size.width) {
  9564. height = size.height;
  9565. width = Math.round(height * engine.getAspectRatio(camera));
  9566. }
  9567. //Assuming here that "size" parameter is a number
  9568. else if (!isNaN(size)) {
  9569. height = size;
  9570. width = size;
  9571. }
  9572. else {
  9573. Tools.Error("Invalid 'size' parameter !");
  9574. return;
  9575. }
  9576. if (!screenshotCanvas) {
  9577. screenshotCanvas = document.createElement('canvas');
  9578. }
  9579. screenshotCanvas.width = width;
  9580. screenshotCanvas.height = height;
  9581. var renderContext = screenshotCanvas.getContext("2d");
  9582. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9583. var newWidth = width;
  9584. var newHeight = newWidth / ratio;
  9585. if (newHeight > height) {
  9586. newHeight = height;
  9587. newWidth = newHeight * ratio;
  9588. }
  9589. var offsetX = Math.max(0, width - newWidth) / 2;
  9590. var offsetY = Math.max(0, height - newHeight) / 2;
  9591. var renderingCanvas = engine.getRenderingCanvas();
  9592. if (renderContext && renderingCanvas) {
  9593. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9594. }
  9595. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9596. };
  9597. /**
  9598. * Generates an image screenshot from the specified camera.
  9599. *
  9600. * @param engine The engine to use for rendering
  9601. * @param camera The camera to use for rendering
  9602. * @param size This parameter can be set to a single number or to an object with the
  9603. * following (optional) properties: precision, width, height. If a single number is passed,
  9604. * it will be used for both width and height. If an object is passed, the screenshot size
  9605. * will be derived from the parameters. The precision property is a multiplier allowing
  9606. * rendering at a higher or lower resolution.
  9607. * @param successCallback The callback receives a single parameter which contains the
  9608. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9609. * src parameter of an <img> to display it.
  9610. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9611. * Check your browser for supported MIME types.
  9612. * @param samples Texture samples (default: 1)
  9613. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9614. * @param fileName A name for for the downloaded file.
  9615. * @constructor
  9616. */
  9617. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9618. if (mimeType === void 0) { mimeType = "image/png"; }
  9619. if (samples === void 0) { samples = 1; }
  9620. if (antialiasing === void 0) { antialiasing = false; }
  9621. var width;
  9622. var height;
  9623. //If a precision value is specified
  9624. if (size.precision) {
  9625. width = Math.round(engine.getRenderWidth() * size.precision);
  9626. height = Math.round(width / engine.getAspectRatio(camera));
  9627. size = { width: width, height: height };
  9628. }
  9629. else if (size.width && size.height) {
  9630. width = size.width;
  9631. height = size.height;
  9632. }
  9633. //If passing only width, computing height to keep display canvas ratio.
  9634. else if (size.width && !size.height) {
  9635. width = size.width;
  9636. height = Math.round(width / engine.getAspectRatio(camera));
  9637. size = { width: width, height: height };
  9638. }
  9639. //If passing only height, computing width to keep display canvas ratio.
  9640. else if (size.height && !size.width) {
  9641. height = size.height;
  9642. width = Math.round(height * engine.getAspectRatio(camera));
  9643. size = { width: width, height: height };
  9644. }
  9645. //Assuming here that "size" parameter is a number
  9646. else if (!isNaN(size)) {
  9647. height = size;
  9648. width = size;
  9649. }
  9650. else {
  9651. Tools.Error("Invalid 'size' parameter !");
  9652. return;
  9653. }
  9654. var scene = camera.getScene();
  9655. var previousCamera = null;
  9656. if (scene.activeCamera !== camera) {
  9657. previousCamera = scene.activeCamera;
  9658. scene.activeCamera = camera;
  9659. }
  9660. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9661. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9662. texture.renderList = null;
  9663. texture.samples = samples;
  9664. if (antialiasing) {
  9665. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9666. }
  9667. texture.onAfterRenderObservable.add(function () {
  9668. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9669. });
  9670. scene.incrementRenderId();
  9671. scene.resetCachedMaterial();
  9672. texture.render(true);
  9673. texture.dispose();
  9674. if (previousCamera) {
  9675. scene.activeCamera = previousCamera;
  9676. }
  9677. camera.getProjectionMatrix(true); // Force cache refresh;
  9678. };
  9679. // XHR response validator for local file scenario
  9680. Tools.ValidateXHRData = function (xhr, dataType) {
  9681. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9682. if (dataType === void 0) { dataType = 7; }
  9683. try {
  9684. if (dataType & 1) {
  9685. if (xhr.responseText && xhr.responseText.length > 0) {
  9686. return true;
  9687. }
  9688. else if (dataType === 1) {
  9689. return false;
  9690. }
  9691. }
  9692. if (dataType & 2) {
  9693. // Check header width and height since there is no "TGA" magic number
  9694. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9695. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9696. return true;
  9697. }
  9698. else if (dataType === 2) {
  9699. return false;
  9700. }
  9701. }
  9702. if (dataType & 4) {
  9703. // Check for the "DDS" magic number
  9704. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9705. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9706. return true;
  9707. }
  9708. else {
  9709. return false;
  9710. }
  9711. }
  9712. }
  9713. catch (e) {
  9714. // Global protection
  9715. }
  9716. return false;
  9717. };
  9718. /**
  9719. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9720. * Be aware Math.random() could cause collisions, but:
  9721. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9722. */
  9723. Tools.RandomId = function () {
  9724. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9725. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9726. return v.toString(16);
  9727. });
  9728. };
  9729. /**
  9730. * Test if the given uri is a base64 string.
  9731. * @param uri The uri to test
  9732. * @return True if the uri is a base64 string or false otherwise.
  9733. */
  9734. Tools.IsBase64 = function (uri) {
  9735. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9736. };
  9737. /**
  9738. * Decode the given base64 uri.
  9739. * @param uri The uri to decode
  9740. * @return The decoded base64 data.
  9741. */
  9742. Tools.DecodeBase64 = function (uri) {
  9743. var decodedString = atob(uri.split(",")[1]);
  9744. var bufferLength = decodedString.length;
  9745. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9746. for (var i = 0; i < bufferLength; i++) {
  9747. bufferView[i] = decodedString.charCodeAt(i);
  9748. }
  9749. return bufferView.buffer;
  9750. };
  9751. Object.defineProperty(Tools, "NoneLogLevel", {
  9752. get: function () {
  9753. return Tools._NoneLogLevel;
  9754. },
  9755. enumerable: true,
  9756. configurable: true
  9757. });
  9758. Object.defineProperty(Tools, "MessageLogLevel", {
  9759. get: function () {
  9760. return Tools._MessageLogLevel;
  9761. },
  9762. enumerable: true,
  9763. configurable: true
  9764. });
  9765. Object.defineProperty(Tools, "WarningLogLevel", {
  9766. get: function () {
  9767. return Tools._WarningLogLevel;
  9768. },
  9769. enumerable: true,
  9770. configurable: true
  9771. });
  9772. Object.defineProperty(Tools, "ErrorLogLevel", {
  9773. get: function () {
  9774. return Tools._ErrorLogLevel;
  9775. },
  9776. enumerable: true,
  9777. configurable: true
  9778. });
  9779. Object.defineProperty(Tools, "AllLogLevel", {
  9780. get: function () {
  9781. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Tools._AddLogEntry = function (entry) {
  9787. Tools._LogCache = entry + Tools._LogCache;
  9788. if (Tools.OnNewCacheEntry) {
  9789. Tools.OnNewCacheEntry(entry);
  9790. }
  9791. };
  9792. Tools._FormatMessage = function (message) {
  9793. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9794. var date = new Date();
  9795. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9796. };
  9797. Tools._LogDisabled = function (message) {
  9798. // nothing to do
  9799. };
  9800. Tools._LogEnabled = function (message) {
  9801. var formattedMessage = Tools._FormatMessage(message);
  9802. console.log("BJS - " + formattedMessage);
  9803. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9804. Tools._AddLogEntry(entry);
  9805. };
  9806. Tools._WarnDisabled = function (message) {
  9807. // nothing to do
  9808. };
  9809. Tools._WarnEnabled = function (message) {
  9810. var formattedMessage = Tools._FormatMessage(message);
  9811. console.warn("BJS - " + formattedMessage);
  9812. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9813. Tools._AddLogEntry(entry);
  9814. };
  9815. Tools._ErrorDisabled = function (message) {
  9816. // nothing to do
  9817. };
  9818. Tools._ErrorEnabled = function (message) {
  9819. Tools.errorsCount++;
  9820. var formattedMessage = Tools._FormatMessage(message);
  9821. console.error("BJS - " + formattedMessage);
  9822. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9823. Tools._AddLogEntry(entry);
  9824. };
  9825. Object.defineProperty(Tools, "LogCache", {
  9826. get: function () {
  9827. return Tools._LogCache;
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Tools.ClearLogCache = function () {
  9833. Tools._LogCache = "";
  9834. Tools.errorsCount = 0;
  9835. };
  9836. Object.defineProperty(Tools, "LogLevels", {
  9837. set: function (level) {
  9838. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9839. Tools.Log = Tools._LogEnabled;
  9840. }
  9841. else {
  9842. Tools.Log = Tools._LogDisabled;
  9843. }
  9844. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9845. Tools.Warn = Tools._WarnEnabled;
  9846. }
  9847. else {
  9848. Tools.Warn = Tools._WarnDisabled;
  9849. }
  9850. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9851. Tools.Error = Tools._ErrorEnabled;
  9852. }
  9853. else {
  9854. Tools.Error = Tools._ErrorDisabled;
  9855. }
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. /**
  9861. * Check if the loaded document was accessed via `file:`-Protocol.
  9862. * @returns boolean
  9863. */
  9864. Tools.IsFileURL = function () {
  9865. return location.protocol === "file:";
  9866. };
  9867. Tools.IsWindowObjectExist = function () {
  9868. return (typeof window) !== "undefined";
  9869. };
  9870. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9871. get: function () {
  9872. return Tools._PerformanceNoneLogLevel;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9878. get: function () {
  9879. return Tools._PerformanceUserMarkLogLevel;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9885. get: function () {
  9886. return Tools._PerformanceConsoleLogLevel;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9892. set: function (level) {
  9893. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9894. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9895. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9896. return;
  9897. }
  9898. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9899. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9900. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9901. return;
  9902. }
  9903. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9904. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9910. };
  9911. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9912. };
  9913. Tools._StartUserMark = function (counterName, condition) {
  9914. if (condition === void 0) { condition = true; }
  9915. if (!Tools._performance) {
  9916. if (!Tools.IsWindowObjectExist()) {
  9917. return;
  9918. }
  9919. Tools._performance = window.performance;
  9920. }
  9921. if (!condition || !Tools._performance.mark) {
  9922. return;
  9923. }
  9924. Tools._performance.mark(counterName + "-Begin");
  9925. };
  9926. Tools._EndUserMark = function (counterName, condition) {
  9927. if (condition === void 0) { condition = true; }
  9928. if (!condition || !Tools._performance.mark) {
  9929. return;
  9930. }
  9931. Tools._performance.mark(counterName + "-End");
  9932. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9933. };
  9934. Tools._StartPerformanceConsole = function (counterName, condition) {
  9935. if (condition === void 0) { condition = true; }
  9936. if (!condition) {
  9937. return;
  9938. }
  9939. Tools._StartUserMark(counterName, condition);
  9940. if (console.time) {
  9941. console.time(counterName);
  9942. }
  9943. };
  9944. Tools._EndPerformanceConsole = function (counterName, condition) {
  9945. if (condition === void 0) { condition = true; }
  9946. if (!condition) {
  9947. return;
  9948. }
  9949. Tools._EndUserMark(counterName, condition);
  9950. if (console.time) {
  9951. console.timeEnd(counterName);
  9952. }
  9953. };
  9954. Object.defineProperty(Tools, "Now", {
  9955. get: function () {
  9956. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9957. return window.performance.now();
  9958. }
  9959. return Date.now();
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. /**
  9965. * This method will return the name of the class used to create the instance of the given object.
  9966. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9967. * @param object the object to get the class name from
  9968. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9969. */
  9970. Tools.GetClassName = function (object, isType) {
  9971. if (isType === void 0) { isType = false; }
  9972. var name = null;
  9973. if (!isType && object.getClassName) {
  9974. name = object.getClassName();
  9975. }
  9976. else {
  9977. if (object instanceof Object) {
  9978. var classObj = isType ? object : Object.getPrototypeOf(object);
  9979. name = classObj.constructor["__bjsclassName__"];
  9980. }
  9981. if (!name) {
  9982. name = typeof object;
  9983. }
  9984. }
  9985. return name;
  9986. };
  9987. Tools.First = function (array, predicate) {
  9988. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9989. var el = array_1[_i];
  9990. if (predicate(el)) {
  9991. return el;
  9992. }
  9993. }
  9994. return null;
  9995. };
  9996. /**
  9997. * This method will return the name of the full name of the class, including its owning module (if any).
  9998. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9999. * @param object the object to get the class name from
  10000. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  10001. */
  10002. Tools.getFullClassName = function (object, isType) {
  10003. if (isType === void 0) { isType = false; }
  10004. var className = null;
  10005. var moduleName = null;
  10006. if (!isType && object.getClassName) {
  10007. className = object.getClassName();
  10008. }
  10009. else {
  10010. if (object instanceof Object) {
  10011. var classObj = isType ? object : Object.getPrototypeOf(object);
  10012. className = classObj.constructor["__bjsclassName__"];
  10013. moduleName = classObj.constructor["__bjsmoduleName__"];
  10014. }
  10015. if (!className) {
  10016. className = typeof object;
  10017. }
  10018. }
  10019. if (!className) {
  10020. return null;
  10021. }
  10022. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10023. };
  10024. /**
  10025. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10026. * @param array
  10027. */
  10028. Tools.arrayOrStringFeeder = function (array) {
  10029. return function (index) {
  10030. if (index >= array.length) {
  10031. return null;
  10032. }
  10033. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10034. if (val && val.getHashCode) {
  10035. val = val.getHashCode();
  10036. }
  10037. if (typeof val === "string") {
  10038. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10039. }
  10040. return val;
  10041. };
  10042. };
  10043. /**
  10044. * Compute the hashCode of a stream of number
  10045. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10046. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10047. * @return the hash code computed
  10048. */
  10049. Tools.hashCodeFromStream = function (feeder) {
  10050. // Based from here: http://stackoverflow.com/a/7616484/802124
  10051. var hash = 0;
  10052. var index = 0;
  10053. var chr = feeder(index++);
  10054. while (chr != null) {
  10055. hash = ((hash << 5) - hash) + chr;
  10056. hash |= 0; // Convert to 32bit integer
  10057. chr = feeder(index++);
  10058. }
  10059. return hash;
  10060. };
  10061. /**
  10062. * Returns a promise that resolves after the given amount of time.
  10063. * @param delay Number of milliseconds to delay
  10064. * @returns Promise that resolves after the given amount of time
  10065. */
  10066. Tools.DelayAsync = function (delay) {
  10067. return new Promise(function (resolve) {
  10068. setTimeout(function () {
  10069. resolve();
  10070. }, delay);
  10071. });
  10072. };
  10073. /**
  10074. * Gets the current gradient from an array of IValueGradient
  10075. * @param ratio defines the current ratio to get
  10076. * @param gradients defines the array of IValueGradient
  10077. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10078. */
  10079. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10080. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10081. var currentGradient = gradients[gradientIndex];
  10082. var nextGradient = gradients[gradientIndex + 1];
  10083. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10084. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10085. updateFunc(currentGradient, nextGradient, scale);
  10086. return;
  10087. }
  10088. }
  10089. // Use last index if over
  10090. var lastIndex = gradients.length - 1;
  10091. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10092. };
  10093. Tools.BaseUrl = "";
  10094. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10095. /**
  10096. * Default behaviour for cors in the application.
  10097. * It can be a string if the expected behavior is identical in the entire app.
  10098. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10099. */
  10100. Tools.CorsBehavior = "anonymous";
  10101. Tools.UseFallbackTexture = true;
  10102. /**
  10103. * Use this object to register external classes like custom textures or material
  10104. * to allow the laoders to instantiate them
  10105. */
  10106. Tools.RegisteredExternalClasses = {};
  10107. // Used in case of a texture loading problem
  10108. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  10109. Tools._tmpFloatArray = new Float32Array(1);
  10110. Tools.PreprocessUrl = function (url) {
  10111. return url;
  10112. };
  10113. // Logs
  10114. Tools._NoneLogLevel = 0;
  10115. Tools._MessageLogLevel = 1;
  10116. Tools._WarningLogLevel = 2;
  10117. Tools._ErrorLogLevel = 4;
  10118. Tools._LogCache = "";
  10119. Tools.errorsCount = 0;
  10120. Tools.Log = Tools._LogEnabled;
  10121. Tools.Warn = Tools._WarnEnabled;
  10122. Tools.Error = Tools._ErrorEnabled;
  10123. // Performances
  10124. Tools._PerformanceNoneLogLevel = 0;
  10125. Tools._PerformanceUserMarkLogLevel = 1;
  10126. Tools._PerformanceConsoleLogLevel = 2;
  10127. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10128. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10129. return Tools;
  10130. }());
  10131. BABYLON.Tools = Tools;
  10132. /**
  10133. * This class is used to track a performance counter which is number based.
  10134. * The user has access to many properties which give statistics of different nature
  10135. *
  10136. * The implementer can track two kinds of Performance Counter: time and count
  10137. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  10138. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  10139. */
  10140. var PerfCounter = /** @class */ (function () {
  10141. function PerfCounter() {
  10142. this._startMonitoringTime = 0;
  10143. this._min = 0;
  10144. this._max = 0;
  10145. this._average = 0;
  10146. this._lastSecAverage = 0;
  10147. this._current = 0;
  10148. this._totalValueCount = 0;
  10149. this._totalAccumulated = 0;
  10150. this._lastSecAccumulated = 0;
  10151. this._lastSecTime = 0;
  10152. this._lastSecValueCount = 0;
  10153. }
  10154. Object.defineProperty(PerfCounter.prototype, "min", {
  10155. /**
  10156. * Returns the smallest value ever
  10157. */
  10158. get: function () {
  10159. return this._min;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(PerfCounter.prototype, "max", {
  10165. /**
  10166. * Returns the biggest value ever
  10167. */
  10168. get: function () {
  10169. return this._max;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(PerfCounter.prototype, "average", {
  10175. /**
  10176. * Returns the average value since the performance counter is running
  10177. */
  10178. get: function () {
  10179. return this._average;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10185. /**
  10186. * Returns the average value of the last second the counter was monitored
  10187. */
  10188. get: function () {
  10189. return this._lastSecAverage;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(PerfCounter.prototype, "current", {
  10195. /**
  10196. * Returns the current value
  10197. */
  10198. get: function () {
  10199. return this._current;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Object.defineProperty(PerfCounter.prototype, "total", {
  10205. get: function () {
  10206. return this._totalAccumulated;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. Object.defineProperty(PerfCounter.prototype, "count", {
  10212. get: function () {
  10213. return this._totalValueCount;
  10214. },
  10215. enumerable: true,
  10216. configurable: true
  10217. });
  10218. /**
  10219. * Call this method to start monitoring a new frame.
  10220. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10221. */
  10222. PerfCounter.prototype.fetchNewFrame = function () {
  10223. this._totalValueCount++;
  10224. this._current = 0;
  10225. this._lastSecValueCount++;
  10226. };
  10227. /**
  10228. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10229. * @param newCount the count value to add to the monitored count
  10230. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10231. */
  10232. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10233. if (!PerfCounter.Enabled) {
  10234. return;
  10235. }
  10236. this._current += newCount;
  10237. if (fetchResult) {
  10238. this._fetchResult();
  10239. }
  10240. };
  10241. /**
  10242. * Start monitoring this performance counter
  10243. */
  10244. PerfCounter.prototype.beginMonitoring = function () {
  10245. if (!PerfCounter.Enabled) {
  10246. return;
  10247. }
  10248. this._startMonitoringTime = Tools.Now;
  10249. };
  10250. /**
  10251. * Compute the time lapsed since the previous beginMonitoring() call.
  10252. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10253. */
  10254. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10255. if (newFrame === void 0) { newFrame = true; }
  10256. if (!PerfCounter.Enabled) {
  10257. return;
  10258. }
  10259. if (newFrame) {
  10260. this.fetchNewFrame();
  10261. }
  10262. var currentTime = Tools.Now;
  10263. this._current = currentTime - this._startMonitoringTime;
  10264. if (newFrame) {
  10265. this._fetchResult();
  10266. }
  10267. };
  10268. PerfCounter.prototype._fetchResult = function () {
  10269. this._totalAccumulated += this._current;
  10270. this._lastSecAccumulated += this._current;
  10271. // Min/Max update
  10272. this._min = Math.min(this._min, this._current);
  10273. this._max = Math.max(this._max, this._current);
  10274. this._average = this._totalAccumulated / this._totalValueCount;
  10275. // Reset last sec?
  10276. var now = Tools.Now;
  10277. if ((now - this._lastSecTime) > 1000) {
  10278. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10279. this._lastSecTime = now;
  10280. this._lastSecAccumulated = 0;
  10281. this._lastSecValueCount = 0;
  10282. }
  10283. };
  10284. PerfCounter.Enabled = true;
  10285. return PerfCounter;
  10286. }());
  10287. BABYLON.PerfCounter = PerfCounter;
  10288. /**
  10289. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10290. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10291. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10292. * @param name The name of the class, case should be preserved
  10293. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10294. */
  10295. function className(name, module) {
  10296. return function (target) {
  10297. target["__bjsclassName__"] = name;
  10298. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10299. };
  10300. }
  10301. BABYLON.className = className;
  10302. /**
  10303. * An implementation of a loop for asynchronous functions.
  10304. */
  10305. var AsyncLoop = /** @class */ (function () {
  10306. /**
  10307. * Constroctor.
  10308. * @param iterations the number of iterations.
  10309. * @param _fn the function to run each iteration
  10310. * @param _successCallback the callback that will be called upon succesful execution
  10311. * @param offset starting offset.
  10312. */
  10313. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10314. if (offset === void 0) { offset = 0; }
  10315. this.iterations = iterations;
  10316. this._fn = _fn;
  10317. this._successCallback = _successCallback;
  10318. this.index = offset - 1;
  10319. this._done = false;
  10320. }
  10321. /**
  10322. * Execute the next iteration. Must be called after the last iteration was finished.
  10323. */
  10324. AsyncLoop.prototype.executeNext = function () {
  10325. if (!this._done) {
  10326. if (this.index + 1 < this.iterations) {
  10327. ++this.index;
  10328. this._fn(this);
  10329. }
  10330. else {
  10331. this.breakLoop();
  10332. }
  10333. }
  10334. };
  10335. /**
  10336. * Break the loop and run the success callback.
  10337. */
  10338. AsyncLoop.prototype.breakLoop = function () {
  10339. this._done = true;
  10340. this._successCallback();
  10341. };
  10342. /**
  10343. * Helper function
  10344. */
  10345. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10346. if (offset === void 0) { offset = 0; }
  10347. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10348. loop.executeNext();
  10349. return loop;
  10350. };
  10351. /**
  10352. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10353. * @param iterations total number of iterations
  10354. * @param syncedIterations number of synchronous iterations in each async iteration.
  10355. * @param fn the function to call each iteration.
  10356. * @param callback a success call back that will be called when iterating stops.
  10357. * @param breakFunction a break condition (optional)
  10358. * @param timeout timeout settings for the setTimeout function. default - 0.
  10359. * @constructor
  10360. */
  10361. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10362. if (timeout === void 0) { timeout = 0; }
  10363. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10364. if (breakFunction && breakFunction())
  10365. loop.breakLoop();
  10366. else {
  10367. setTimeout(function () {
  10368. for (var i = 0; i < syncedIterations; ++i) {
  10369. var iteration = (loop.index * syncedIterations) + i;
  10370. if (iteration >= iterations)
  10371. break;
  10372. fn(iteration);
  10373. if (breakFunction && breakFunction()) {
  10374. loop.breakLoop();
  10375. break;
  10376. }
  10377. }
  10378. loop.executeNext();
  10379. }, timeout);
  10380. }
  10381. }, callback);
  10382. };
  10383. return AsyncLoop;
  10384. }());
  10385. BABYLON.AsyncLoop = AsyncLoop;
  10386. })(BABYLON || (BABYLON = {}));
  10387. //# sourceMappingURL=babylon.tools.js.map
  10388. var BABYLON;
  10389. (function (BABYLON) {
  10390. var PromiseStates;
  10391. (function (PromiseStates) {
  10392. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10393. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10394. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10395. })(PromiseStates || (PromiseStates = {}));
  10396. var FulFillmentAgregator = /** @class */ (function () {
  10397. function FulFillmentAgregator() {
  10398. this.count = 0;
  10399. this.target = 0;
  10400. this.results = [];
  10401. }
  10402. return FulFillmentAgregator;
  10403. }());
  10404. var InternalPromise = /** @class */ (function () {
  10405. function InternalPromise(resolver) {
  10406. var _this = this;
  10407. this._state = PromiseStates.Pending;
  10408. this._children = new Array();
  10409. this._rejectWasConsumed = false;
  10410. if (!resolver) {
  10411. return;
  10412. }
  10413. try {
  10414. resolver(function (value) {
  10415. _this._resolve(value);
  10416. }, function (reason) {
  10417. _this._reject(reason);
  10418. });
  10419. }
  10420. catch (e) {
  10421. this._reject(e);
  10422. }
  10423. }
  10424. Object.defineProperty(InternalPromise.prototype, "_result", {
  10425. get: function () {
  10426. return this._resultValue;
  10427. },
  10428. set: function (value) {
  10429. this._resultValue = value;
  10430. if (this._parent && this._parent._result === undefined) {
  10431. this._parent._result = value;
  10432. }
  10433. },
  10434. enumerable: true,
  10435. configurable: true
  10436. });
  10437. InternalPromise.prototype.catch = function (onRejected) {
  10438. return this.then(undefined, onRejected);
  10439. };
  10440. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10441. var _this = this;
  10442. var newPromise = new InternalPromise();
  10443. newPromise._onFulfilled = onFulfilled;
  10444. newPromise._onRejected = onRejected;
  10445. // Composition
  10446. this._children.push(newPromise);
  10447. newPromise._parent = this;
  10448. if (this._state !== PromiseStates.Pending) {
  10449. BABYLON.Tools.SetImmediate(function () {
  10450. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10451. var returnedValue = newPromise._resolve(_this._result);
  10452. if (returnedValue !== undefined && returnedValue !== null) {
  10453. if (returnedValue._state !== undefined) {
  10454. var returnedPromise = returnedValue;
  10455. newPromise._children.push(returnedPromise);
  10456. returnedPromise._parent = newPromise;
  10457. newPromise = returnedPromise;
  10458. }
  10459. else {
  10460. newPromise._result = returnedValue;
  10461. }
  10462. }
  10463. }
  10464. else {
  10465. newPromise._reject(_this._reason);
  10466. }
  10467. });
  10468. }
  10469. return newPromise;
  10470. };
  10471. InternalPromise.prototype._moveChildren = function (children) {
  10472. var _this = this;
  10473. var _a;
  10474. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10475. this._children.forEach(function (child) {
  10476. child._parent = _this;
  10477. });
  10478. if (this._state === PromiseStates.Fulfilled) {
  10479. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10480. var child = _b[_i];
  10481. child._resolve(this._result);
  10482. }
  10483. }
  10484. else if (this._state === PromiseStates.Rejected) {
  10485. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10486. var child = _d[_c];
  10487. child._reject(this._reason);
  10488. }
  10489. }
  10490. };
  10491. InternalPromise.prototype._resolve = function (value) {
  10492. try {
  10493. this._state = PromiseStates.Fulfilled;
  10494. var returnedValue = null;
  10495. if (this._onFulfilled) {
  10496. returnedValue = this._onFulfilled(value);
  10497. }
  10498. if (returnedValue !== undefined && returnedValue !== null) {
  10499. if (returnedValue._state !== undefined) {
  10500. // Transmit children
  10501. var returnedPromise = returnedValue;
  10502. returnedPromise._parent = this;
  10503. returnedPromise._moveChildren(this._children);
  10504. value = returnedPromise._result;
  10505. }
  10506. else {
  10507. value = returnedValue;
  10508. }
  10509. }
  10510. this._result = value;
  10511. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10512. var child = _a[_i];
  10513. child._resolve(value);
  10514. }
  10515. this._children.length = 0;
  10516. delete this._onFulfilled;
  10517. delete this._onRejected;
  10518. }
  10519. catch (e) {
  10520. this._reject(e, true);
  10521. }
  10522. };
  10523. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10524. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10525. this._state = PromiseStates.Rejected;
  10526. this._reason = reason;
  10527. if (this._onRejected && !onLocalThrow) {
  10528. try {
  10529. this._onRejected(reason);
  10530. this._rejectWasConsumed = true;
  10531. }
  10532. catch (e) {
  10533. reason = e;
  10534. }
  10535. }
  10536. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10537. var child = _a[_i];
  10538. if (this._rejectWasConsumed) {
  10539. child._resolve(null);
  10540. }
  10541. else {
  10542. child._reject(reason);
  10543. }
  10544. }
  10545. this._children.length = 0;
  10546. delete this._onFulfilled;
  10547. delete this._onRejected;
  10548. };
  10549. InternalPromise.resolve = function (value) {
  10550. var newPromise = new InternalPromise();
  10551. newPromise._resolve(value);
  10552. return newPromise;
  10553. };
  10554. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10555. promise.then(function (value) {
  10556. agregator.results[index] = value;
  10557. agregator.count++;
  10558. if (agregator.count === agregator.target) {
  10559. agregator.rootPromise._resolve(agregator.results);
  10560. }
  10561. return null;
  10562. }, function (reason) {
  10563. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10564. agregator.rootPromise._reject(reason);
  10565. }
  10566. });
  10567. };
  10568. InternalPromise.all = function (promises) {
  10569. var newPromise = new InternalPromise();
  10570. var agregator = new FulFillmentAgregator();
  10571. agregator.target = promises.length;
  10572. agregator.rootPromise = newPromise;
  10573. if (promises.length) {
  10574. for (var index = 0; index < promises.length; index++) {
  10575. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10576. }
  10577. }
  10578. else {
  10579. newPromise._resolve([]);
  10580. }
  10581. return newPromise;
  10582. };
  10583. InternalPromise.race = function (promises) {
  10584. var newPromise = new InternalPromise();
  10585. if (promises.length) {
  10586. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10587. var promise = promises_1[_i];
  10588. promise.then(function (value) {
  10589. if (newPromise) {
  10590. newPromise._resolve(value);
  10591. newPromise = null;
  10592. }
  10593. return null;
  10594. }, function (reason) {
  10595. if (newPromise) {
  10596. newPromise._reject(reason);
  10597. newPromise = null;
  10598. }
  10599. });
  10600. }
  10601. }
  10602. return newPromise;
  10603. };
  10604. return InternalPromise;
  10605. }());
  10606. /**
  10607. * Helper class that provides a small promise polyfill
  10608. */
  10609. var PromisePolyfill = /** @class */ (function () {
  10610. function PromisePolyfill() {
  10611. }
  10612. /**
  10613. * Static function used to check if the polyfill is required
  10614. * If this is the case then the function will inject the polyfill to window.Promise
  10615. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10616. */
  10617. PromisePolyfill.Apply = function (force) {
  10618. if (force === void 0) { force = false; }
  10619. if (force || typeof Promise === 'undefined') {
  10620. var root = window;
  10621. root.Promise = InternalPromise;
  10622. }
  10623. };
  10624. return PromisePolyfill;
  10625. }());
  10626. BABYLON.PromisePolyfill = PromisePolyfill;
  10627. })(BABYLON || (BABYLON = {}));
  10628. //# sourceMappingURL=babylon.promise.js.map
  10629. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10630. var BABYLON;
  10631. (function (BABYLON) {
  10632. /**
  10633. * Helper class to push actions to a pool of workers.
  10634. */
  10635. var WorkerPool = /** @class */ (function () {
  10636. /**
  10637. * Constructor
  10638. * @param workers Array of workers to use for actions
  10639. */
  10640. function WorkerPool(workers) {
  10641. this._pendingActions = new Array();
  10642. this._workerInfos = workers.map(function (worker) { return ({
  10643. worker: worker,
  10644. active: false
  10645. }); });
  10646. }
  10647. /**
  10648. * Terminates all workers and clears any pending actions.
  10649. */
  10650. WorkerPool.prototype.dispose = function () {
  10651. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10652. var workerInfo = _a[_i];
  10653. workerInfo.worker.terminate();
  10654. }
  10655. delete this._workerInfos;
  10656. delete this._pendingActions;
  10657. };
  10658. /**
  10659. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10660. * pended until a worker has completed its action.
  10661. * @param action The action to perform. Call onComplete when the action is complete.
  10662. */
  10663. WorkerPool.prototype.push = function (action) {
  10664. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10665. var workerInfo = _a[_i];
  10666. if (!workerInfo.active) {
  10667. this._execute(workerInfo, action);
  10668. return;
  10669. }
  10670. }
  10671. this._pendingActions.push(action);
  10672. };
  10673. WorkerPool.prototype._execute = function (workerInfo, action) {
  10674. var _this = this;
  10675. workerInfo.active = true;
  10676. action(workerInfo.worker, function () {
  10677. workerInfo.active = false;
  10678. var nextAction = _this._pendingActions.shift();
  10679. if (nextAction) {
  10680. _this._execute(workerInfo, nextAction);
  10681. }
  10682. });
  10683. };
  10684. return WorkerPool;
  10685. }());
  10686. BABYLON.WorkerPool = WorkerPool;
  10687. })(BABYLON || (BABYLON = {}));
  10688. //# sourceMappingURL=babylon.workerPool.js.map
  10689. var BABYLON;
  10690. (function (BABYLON) {
  10691. /**
  10692. * @hidden
  10693. **/
  10694. var _AlphaState = /** @class */ (function () {
  10695. /**
  10696. * Initializes the state.
  10697. */
  10698. function _AlphaState() {
  10699. this._isAlphaBlendDirty = false;
  10700. this._isBlendFunctionParametersDirty = false;
  10701. this._isBlendEquationParametersDirty = false;
  10702. this._isBlendConstantsDirty = false;
  10703. this._alphaBlend = false;
  10704. this._blendFunctionParameters = new Array(4);
  10705. this._blendEquationParameters = new Array(2);
  10706. this._blendConstants = new Array(4);
  10707. this.reset();
  10708. }
  10709. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10710. get: function () {
  10711. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10717. get: function () {
  10718. return this._alphaBlend;
  10719. },
  10720. set: function (value) {
  10721. if (this._alphaBlend === value) {
  10722. return;
  10723. }
  10724. this._alphaBlend = value;
  10725. this._isAlphaBlendDirty = true;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10731. if (this._blendConstants[0] === r &&
  10732. this._blendConstants[1] === g &&
  10733. this._blendConstants[2] === b &&
  10734. this._blendConstants[3] === a) {
  10735. return;
  10736. }
  10737. this._blendConstants[0] = r;
  10738. this._blendConstants[1] = g;
  10739. this._blendConstants[2] = b;
  10740. this._blendConstants[3] = a;
  10741. this._isBlendConstantsDirty = true;
  10742. };
  10743. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10744. if (this._blendFunctionParameters[0] === value0 &&
  10745. this._blendFunctionParameters[1] === value1 &&
  10746. this._blendFunctionParameters[2] === value2 &&
  10747. this._blendFunctionParameters[3] === value3) {
  10748. return;
  10749. }
  10750. this._blendFunctionParameters[0] = value0;
  10751. this._blendFunctionParameters[1] = value1;
  10752. this._blendFunctionParameters[2] = value2;
  10753. this._blendFunctionParameters[3] = value3;
  10754. this._isBlendFunctionParametersDirty = true;
  10755. };
  10756. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10757. if (this._blendEquationParameters[0] === rgb &&
  10758. this._blendEquationParameters[1] === alpha) {
  10759. return;
  10760. }
  10761. this._blendEquationParameters[0] = rgb;
  10762. this._blendEquationParameters[1] = alpha;
  10763. this._isBlendEquationParametersDirty = true;
  10764. };
  10765. _AlphaState.prototype.reset = function () {
  10766. this._alphaBlend = false;
  10767. this._blendFunctionParameters[0] = null;
  10768. this._blendFunctionParameters[1] = null;
  10769. this._blendFunctionParameters[2] = null;
  10770. this._blendFunctionParameters[3] = null;
  10771. this._blendEquationParameters[0] = null;
  10772. this._blendEquationParameters[1] = null;
  10773. this._blendConstants[0] = null;
  10774. this._blendConstants[1] = null;
  10775. this._blendConstants[2] = null;
  10776. this._blendConstants[3] = null;
  10777. this._isAlphaBlendDirty = true;
  10778. this._isBlendFunctionParametersDirty = false;
  10779. this._isBlendEquationParametersDirty = false;
  10780. this._isBlendConstantsDirty = false;
  10781. };
  10782. _AlphaState.prototype.apply = function (gl) {
  10783. if (!this.isDirty) {
  10784. return;
  10785. }
  10786. // Alpha blend
  10787. if (this._isAlphaBlendDirty) {
  10788. if (this._alphaBlend) {
  10789. gl.enable(gl.BLEND);
  10790. }
  10791. else {
  10792. gl.disable(gl.BLEND);
  10793. }
  10794. this._isAlphaBlendDirty = false;
  10795. }
  10796. // Alpha function
  10797. if (this._isBlendFunctionParametersDirty) {
  10798. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10799. this._isBlendFunctionParametersDirty = false;
  10800. }
  10801. // Alpha equation
  10802. if (this._isBlendEquationParametersDirty) {
  10803. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10804. this._isBlendEquationParametersDirty = false;
  10805. }
  10806. // Constants
  10807. if (this._isBlendConstantsDirty) {
  10808. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10809. this._isBlendConstantsDirty = false;
  10810. }
  10811. };
  10812. return _AlphaState;
  10813. }());
  10814. BABYLON._AlphaState = _AlphaState;
  10815. })(BABYLON || (BABYLON = {}));
  10816. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10817. var BABYLON;
  10818. (function (BABYLON) {
  10819. /**
  10820. * @hidden
  10821. **/
  10822. var _DepthCullingState = /** @class */ (function () {
  10823. /**
  10824. * Initializes the state.
  10825. */
  10826. function _DepthCullingState() {
  10827. this._isDepthTestDirty = false;
  10828. this._isDepthMaskDirty = false;
  10829. this._isDepthFuncDirty = false;
  10830. this._isCullFaceDirty = false;
  10831. this._isCullDirty = false;
  10832. this._isZOffsetDirty = false;
  10833. this._isFrontFaceDirty = false;
  10834. this.reset();
  10835. }
  10836. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10837. get: function () {
  10838. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10844. get: function () {
  10845. return this._zOffset;
  10846. },
  10847. set: function (value) {
  10848. if (this._zOffset === value) {
  10849. return;
  10850. }
  10851. this._zOffset = value;
  10852. this._isZOffsetDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10858. get: function () {
  10859. return this._cullFace;
  10860. },
  10861. set: function (value) {
  10862. if (this._cullFace === value) {
  10863. return;
  10864. }
  10865. this._cullFace = value;
  10866. this._isCullFaceDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10872. get: function () {
  10873. return this._cull;
  10874. },
  10875. set: function (value) {
  10876. if (this._cull === value) {
  10877. return;
  10878. }
  10879. this._cull = value;
  10880. this._isCullDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10886. get: function () {
  10887. return this._depthFunc;
  10888. },
  10889. set: function (value) {
  10890. if (this._depthFunc === value) {
  10891. return;
  10892. }
  10893. this._depthFunc = value;
  10894. this._isDepthFuncDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10900. get: function () {
  10901. return this._depthMask;
  10902. },
  10903. set: function (value) {
  10904. if (this._depthMask === value) {
  10905. return;
  10906. }
  10907. this._depthMask = value;
  10908. this._isDepthMaskDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10914. get: function () {
  10915. return this._depthTest;
  10916. },
  10917. set: function (value) {
  10918. if (this._depthTest === value) {
  10919. return;
  10920. }
  10921. this._depthTest = value;
  10922. this._isDepthTestDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10928. get: function () {
  10929. return this._frontFace;
  10930. },
  10931. set: function (value) {
  10932. if (this._frontFace === value) {
  10933. return;
  10934. }
  10935. this._frontFace = value;
  10936. this._isFrontFaceDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. _DepthCullingState.prototype.reset = function () {
  10942. this._depthMask = true;
  10943. this._depthTest = true;
  10944. this._depthFunc = null;
  10945. this._cullFace = null;
  10946. this._cull = null;
  10947. this._zOffset = 0;
  10948. this._frontFace = null;
  10949. this._isDepthTestDirty = true;
  10950. this._isDepthMaskDirty = true;
  10951. this._isDepthFuncDirty = false;
  10952. this._isCullFaceDirty = false;
  10953. this._isCullDirty = false;
  10954. this._isZOffsetDirty = false;
  10955. this._isFrontFaceDirty = false;
  10956. };
  10957. _DepthCullingState.prototype.apply = function (gl) {
  10958. if (!this.isDirty) {
  10959. return;
  10960. }
  10961. // Cull
  10962. if (this._isCullDirty) {
  10963. if (this.cull) {
  10964. gl.enable(gl.CULL_FACE);
  10965. }
  10966. else {
  10967. gl.disable(gl.CULL_FACE);
  10968. }
  10969. this._isCullDirty = false;
  10970. }
  10971. // Cull face
  10972. if (this._isCullFaceDirty) {
  10973. gl.cullFace(this.cullFace);
  10974. this._isCullFaceDirty = false;
  10975. }
  10976. // Depth mask
  10977. if (this._isDepthMaskDirty) {
  10978. gl.depthMask(this.depthMask);
  10979. this._isDepthMaskDirty = false;
  10980. }
  10981. // Depth test
  10982. if (this._isDepthTestDirty) {
  10983. if (this.depthTest) {
  10984. gl.enable(gl.DEPTH_TEST);
  10985. }
  10986. else {
  10987. gl.disable(gl.DEPTH_TEST);
  10988. }
  10989. this._isDepthTestDirty = false;
  10990. }
  10991. // Depth func
  10992. if (this._isDepthFuncDirty) {
  10993. gl.depthFunc(this.depthFunc);
  10994. this._isDepthFuncDirty = false;
  10995. }
  10996. // zOffset
  10997. if (this._isZOffsetDirty) {
  10998. if (this.zOffset) {
  10999. gl.enable(gl.POLYGON_OFFSET_FILL);
  11000. gl.polygonOffset(this.zOffset, 0);
  11001. }
  11002. else {
  11003. gl.disable(gl.POLYGON_OFFSET_FILL);
  11004. }
  11005. this._isZOffsetDirty = false;
  11006. }
  11007. // Front face
  11008. if (this._isFrontFaceDirty) {
  11009. gl.frontFace(this.frontFace);
  11010. this._isFrontFaceDirty = false;
  11011. }
  11012. };
  11013. return _DepthCullingState;
  11014. }());
  11015. BABYLON._DepthCullingState = _DepthCullingState;
  11016. })(BABYLON || (BABYLON = {}));
  11017. //# sourceMappingURL=babylon.depthCullingState.js.map
  11018. var BABYLON;
  11019. (function (BABYLON) {
  11020. /**
  11021. * @hidden
  11022. **/
  11023. var _StencilState = /** @class */ (function () {
  11024. function _StencilState() {
  11025. this._isStencilTestDirty = false;
  11026. this._isStencilMaskDirty = false;
  11027. this._isStencilFuncDirty = false;
  11028. this._isStencilOpDirty = false;
  11029. this.reset();
  11030. }
  11031. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11032. get: function () {
  11033. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11039. get: function () {
  11040. return this._stencilFunc;
  11041. },
  11042. set: function (value) {
  11043. if (this._stencilFunc === value) {
  11044. return;
  11045. }
  11046. this._stencilFunc = value;
  11047. this._isStencilFuncDirty = true;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11053. get: function () {
  11054. return this._stencilFuncRef;
  11055. },
  11056. set: function (value) {
  11057. if (this._stencilFuncRef === value) {
  11058. return;
  11059. }
  11060. this._stencilFuncRef = value;
  11061. this._isStencilFuncDirty = true;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11067. get: function () {
  11068. return this._stencilFuncMask;
  11069. },
  11070. set: function (value) {
  11071. if (this._stencilFuncMask === value) {
  11072. return;
  11073. }
  11074. this._stencilFuncMask = value;
  11075. this._isStencilFuncDirty = true;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11081. get: function () {
  11082. return this._stencilOpStencilFail;
  11083. },
  11084. set: function (value) {
  11085. if (this._stencilOpStencilFail === value) {
  11086. return;
  11087. }
  11088. this._stencilOpStencilFail = value;
  11089. this._isStencilOpDirty = true;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11095. get: function () {
  11096. return this._stencilOpDepthFail;
  11097. },
  11098. set: function (value) {
  11099. if (this._stencilOpDepthFail === value) {
  11100. return;
  11101. }
  11102. this._stencilOpDepthFail = value;
  11103. this._isStencilOpDirty = true;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11109. get: function () {
  11110. return this._stencilOpStencilDepthPass;
  11111. },
  11112. set: function (value) {
  11113. if (this._stencilOpStencilDepthPass === value) {
  11114. return;
  11115. }
  11116. this._stencilOpStencilDepthPass = value;
  11117. this._isStencilOpDirty = true;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11123. get: function () {
  11124. return this._stencilMask;
  11125. },
  11126. set: function (value) {
  11127. if (this._stencilMask === value) {
  11128. return;
  11129. }
  11130. this._stencilMask = value;
  11131. this._isStencilMaskDirty = true;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11137. get: function () {
  11138. return this._stencilTest;
  11139. },
  11140. set: function (value) {
  11141. if (this._stencilTest === value) {
  11142. return;
  11143. }
  11144. this._stencilTest = value;
  11145. this._isStencilTestDirty = true;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. _StencilState.prototype.reset = function () {
  11151. this._stencilTest = false;
  11152. this._stencilMask = 0xFF;
  11153. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11154. this._stencilFuncRef = 1;
  11155. this._stencilFuncMask = 0xFF;
  11156. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11157. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11158. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11159. this._isStencilTestDirty = true;
  11160. this._isStencilMaskDirty = true;
  11161. this._isStencilFuncDirty = true;
  11162. this._isStencilOpDirty = true;
  11163. };
  11164. _StencilState.prototype.apply = function (gl) {
  11165. if (!this.isDirty) {
  11166. return;
  11167. }
  11168. // Stencil test
  11169. if (this._isStencilTestDirty) {
  11170. if (this.stencilTest) {
  11171. gl.enable(gl.STENCIL_TEST);
  11172. }
  11173. else {
  11174. gl.disable(gl.STENCIL_TEST);
  11175. }
  11176. this._isStencilTestDirty = false;
  11177. }
  11178. // Stencil mask
  11179. if (this._isStencilMaskDirty) {
  11180. gl.stencilMask(this.stencilMask);
  11181. this._isStencilMaskDirty = false;
  11182. }
  11183. // Stencil func
  11184. if (this._isStencilFuncDirty) {
  11185. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11186. this._isStencilFuncDirty = false;
  11187. }
  11188. // Stencil op
  11189. if (this._isStencilOpDirty) {
  11190. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11191. this._isStencilOpDirty = false;
  11192. }
  11193. };
  11194. return _StencilState;
  11195. }());
  11196. BABYLON._StencilState = _StencilState;
  11197. })(BABYLON || (BABYLON = {}));
  11198. //# sourceMappingURL=babylon.stencilState.js.map
  11199. var __assign = (this && this.__assign) || function () {
  11200. __assign = Object.assign || function(t) {
  11201. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11202. s = arguments[i];
  11203. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11204. t[p] = s[p];
  11205. }
  11206. return t;
  11207. };
  11208. return __assign.apply(this, arguments);
  11209. };
  11210. var BABYLON;
  11211. (function (BABYLON) {
  11212. /**
  11213. * Keeps track of all the buffer info used in engine.
  11214. */
  11215. var BufferPointer = /** @class */ (function () {
  11216. function BufferPointer() {
  11217. }
  11218. return BufferPointer;
  11219. }());
  11220. /**
  11221. * Interface for attribute information associated with buffer instanciation
  11222. */
  11223. var InstancingAttributeInfo = /** @class */ (function () {
  11224. function InstancingAttributeInfo() {
  11225. }
  11226. return InstancingAttributeInfo;
  11227. }());
  11228. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11229. /**
  11230. * Define options used to create a render target texture
  11231. */
  11232. var RenderTargetCreationOptions = /** @class */ (function () {
  11233. function RenderTargetCreationOptions() {
  11234. }
  11235. return RenderTargetCreationOptions;
  11236. }());
  11237. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11238. /**
  11239. * Define options used to create a depth texture
  11240. */
  11241. var DepthTextureCreationOptions = /** @class */ (function () {
  11242. function DepthTextureCreationOptions() {
  11243. }
  11244. return DepthTextureCreationOptions;
  11245. }());
  11246. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11247. /**
  11248. * Class used to describe the capabilities of the engine relatively to the current browser
  11249. */
  11250. var EngineCapabilities = /** @class */ (function () {
  11251. function EngineCapabilities() {
  11252. }
  11253. return EngineCapabilities;
  11254. }());
  11255. BABYLON.EngineCapabilities = EngineCapabilities;
  11256. /**
  11257. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11258. */
  11259. var Engine = /** @class */ (function () {
  11260. /**
  11261. * Creates a new engine
  11262. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11263. * @param antialias defines enable antialiasing (default: false)
  11264. * @param options defines further options to be sent to the getContext() function
  11265. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11266. */
  11267. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11268. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11269. var _this = this;
  11270. // Public members
  11271. /**
  11272. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11273. */
  11274. this.forcePOTTextures = false;
  11275. /**
  11276. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11277. */
  11278. this.isFullscreen = false;
  11279. /**
  11280. * Gets a boolean indicating if the pointer is currently locked
  11281. */
  11282. this.isPointerLock = false;
  11283. /**
  11284. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11285. */
  11286. this.cullBackFaces = true;
  11287. /**
  11288. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11289. */
  11290. this.renderEvenInBackground = true;
  11291. /**
  11292. * Gets or sets a boolean indicating that cache can be kept between frames
  11293. */
  11294. this.preventCacheWipeBetweenFrames = false;
  11295. /**
  11296. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11297. **/
  11298. this.enableOfflineSupport = false;
  11299. /**
  11300. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11301. **/
  11302. this.disableManifestCheck = false;
  11303. /**
  11304. * Gets the list of created scenes
  11305. */
  11306. this.scenes = new Array();
  11307. /**
  11308. * Gets the list of created postprocesses
  11309. */
  11310. this.postProcesses = new Array();
  11311. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11312. this.validateShaderPrograms = false;
  11313. // Observables
  11314. /**
  11315. * Observable event triggered each time the rendering canvas is resized
  11316. */
  11317. this.onResizeObservable = new BABYLON.Observable();
  11318. /**
  11319. * Observable event triggered each time the canvas loses focus
  11320. */
  11321. this.onCanvasBlurObservable = new BABYLON.Observable();
  11322. /**
  11323. * Observable event triggered each time the canvas gains focus
  11324. */
  11325. this.onCanvasFocusObservable = new BABYLON.Observable();
  11326. /**
  11327. * Observable event triggered each time the canvas receives pointerout event
  11328. */
  11329. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11330. /**
  11331. * Observable event triggered before each texture is initialized
  11332. */
  11333. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11334. //WebVR
  11335. this._vrDisplay = undefined;
  11336. this._vrSupported = false;
  11337. this._vrExclusivePointerMode = false;
  11338. // Uniform buffers list
  11339. /**
  11340. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11341. */
  11342. this.disableUniformBuffers = false;
  11343. /** @hidden */
  11344. this._uniformBuffers = new Array();
  11345. // Observables
  11346. /**
  11347. * Observable raised when the engine begins a new frame
  11348. */
  11349. this.onBeginFrameObservable = new BABYLON.Observable();
  11350. /**
  11351. * Observable raised when the engine ends the current frame
  11352. */
  11353. this.onEndFrameObservable = new BABYLON.Observable();
  11354. /**
  11355. * Observable raised when the engine is about to compile a shader
  11356. */
  11357. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11358. /**
  11359. * Observable raised when the engine has jsut compiled a shader
  11360. */
  11361. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11362. this._windowIsBackground = false;
  11363. this._webGLVersion = 1.0;
  11364. /** @hidden */
  11365. this._badOS = false;
  11366. /** @hidden */
  11367. this._badDesktopOS = false;
  11368. /**
  11369. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11370. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11371. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11372. */
  11373. this.disableTextureBindingOptimization = false;
  11374. /**
  11375. * Observable signaled when VR display mode changes
  11376. */
  11377. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11378. /**
  11379. * Observable signaled when VR request present is complete
  11380. */
  11381. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11382. /**
  11383. * Observable signaled when VR request present starts
  11384. */
  11385. this.onVRRequestPresentStart = new BABYLON.Observable();
  11386. this._colorWrite = true;
  11387. /** @hidden */
  11388. this._drawCalls = new BABYLON.PerfCounter();
  11389. /** @hidden */
  11390. this._textureCollisions = new BABYLON.PerfCounter();
  11391. this._renderingQueueLaunched = false;
  11392. this._activeRenderLoops = new Array();
  11393. // Deterministic lockstepMaxSteps
  11394. this._deterministicLockstep = false;
  11395. this._lockstepMaxSteps = 4;
  11396. // Lost context
  11397. /**
  11398. * Observable signaled when a context lost event is raised
  11399. */
  11400. this.onContextLostObservable = new BABYLON.Observable();
  11401. /**
  11402. * Observable signaled when a context restored event is raised
  11403. */
  11404. this.onContextRestoredObservable = new BABYLON.Observable();
  11405. this._contextWasLost = false;
  11406. this._doNotHandleContextLost = false;
  11407. // FPS
  11408. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11409. this._fps = 60;
  11410. this._deltaTime = 0;
  11411. /**
  11412. * Turn this value on if you want to pause FPS computation when in background
  11413. */
  11414. this.disablePerformanceMonitorInBackground = false;
  11415. // States
  11416. /** @hidden */
  11417. this._depthCullingState = new BABYLON._DepthCullingState();
  11418. /** @hidden */
  11419. this._stencilState = new BABYLON._StencilState();
  11420. /** @hidden */
  11421. this._alphaState = new BABYLON._AlphaState();
  11422. /** @hidden */
  11423. this._alphaMode = Engine.ALPHA_DISABLE;
  11424. // Cache
  11425. this._internalTexturesCache = new Array();
  11426. /** @hidden */
  11427. this._activeChannel = 0;
  11428. this._currentTextureChannel = -1;
  11429. /** @hidden */
  11430. this._boundTexturesCache = {};
  11431. this._compiledEffects = {};
  11432. this._vertexAttribArraysEnabled = [];
  11433. this._uintIndicesCurrentlySet = false;
  11434. this._currentBoundBuffer = new Array();
  11435. /** @hidden */
  11436. this._currentFramebuffer = null;
  11437. this._currentBufferPointers = new Array();
  11438. this._currentInstanceLocations = new Array();
  11439. this._currentInstanceBuffers = new Array();
  11440. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11441. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11442. this._vaoRecordInProgress = false;
  11443. this._mustWipeVertexAttributes = false;
  11444. this._nextFreeTextureSlots = new Array();
  11445. this._maxSimultaneousTextures = 0;
  11446. this._activeRequests = new Array();
  11447. // Hardware supported Compressed Textures
  11448. this._texturesSupported = new Array();
  11449. /**
  11450. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11451. */
  11452. this.premultipliedAlpha = true;
  11453. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11454. this._onVRFullScreenTriggered = function () {
  11455. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11456. //get the old size before we change
  11457. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11458. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11459. //get the width and height, change the render size
  11460. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11461. _this.setHardwareScalingLevel(1);
  11462. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11463. }
  11464. else {
  11465. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11466. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11467. }
  11468. };
  11469. this._unpackFlipYCached = null;
  11470. /**
  11471. * In case you are sharing the context with other applications, it might
  11472. * be interested to not cache the unpack flip y state to ensure a consistent
  11473. * value would be set.
  11474. */
  11475. this.enableUnpackFlipYCached = true;
  11476. this._boundUniforms = {};
  11477. // Register promises
  11478. BABYLON.PromisePolyfill.Apply();
  11479. var canvas = null;
  11480. Engine.Instances.push(this);
  11481. if (!canvasOrContext) {
  11482. return;
  11483. }
  11484. options = options || {};
  11485. if (canvasOrContext.getContext) {
  11486. canvas = canvasOrContext;
  11487. this._renderingCanvas = canvas;
  11488. if (antialias != null) {
  11489. options.antialias = antialias;
  11490. }
  11491. if (options.deterministicLockstep === undefined) {
  11492. options.deterministicLockstep = false;
  11493. }
  11494. if (options.lockstepMaxSteps === undefined) {
  11495. options.lockstepMaxSteps = 4;
  11496. }
  11497. if (options.preserveDrawingBuffer === undefined) {
  11498. options.preserveDrawingBuffer = false;
  11499. }
  11500. if (options.audioEngine === undefined) {
  11501. options.audioEngine = true;
  11502. }
  11503. if (options.stencil === undefined) {
  11504. options.stencil = true;
  11505. }
  11506. if (options.premultipliedAlpha === false) {
  11507. this.premultipliedAlpha = false;
  11508. }
  11509. this._deterministicLockstep = options.deterministicLockstep;
  11510. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11511. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11512. // Exceptions
  11513. if (navigator && navigator.userAgent) {
  11514. var ua = navigator.userAgent;
  11515. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11516. var exception = _a[_i];
  11517. var key = exception.key;
  11518. var targets = exception.targets;
  11519. if (ua.indexOf(key) > -1) {
  11520. if (exception.capture && exception.captureConstraint) {
  11521. var capture = exception.capture;
  11522. var constraint = exception.captureConstraint;
  11523. var regex = new RegExp(capture);
  11524. var matches = regex.exec(ua);
  11525. if (matches && matches.length > 0) {
  11526. var capturedValue = parseInt(matches[matches.length - 1]);
  11527. if (capturedValue >= constraint) {
  11528. continue;
  11529. }
  11530. }
  11531. }
  11532. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11533. var target = targets_1[_b];
  11534. switch (target) {
  11535. case "uniformBuffer":
  11536. this.disableUniformBuffers = true;
  11537. break;
  11538. case "textureBindingOptimization":
  11539. this.disableTextureBindingOptimization = true;
  11540. break;
  11541. }
  11542. }
  11543. }
  11544. }
  11545. }
  11546. // GL
  11547. if (!options.disableWebGL2Support) {
  11548. try {
  11549. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11550. if (this._gl) {
  11551. this._webGLVersion = 2.0;
  11552. }
  11553. }
  11554. catch (e) {
  11555. // Do nothing
  11556. }
  11557. }
  11558. if (!this._gl) {
  11559. if (!canvas) {
  11560. throw new Error("The provided canvas is null or undefined.");
  11561. }
  11562. try {
  11563. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11564. }
  11565. catch (e) {
  11566. throw new Error("WebGL not supported");
  11567. }
  11568. }
  11569. if (!this._gl) {
  11570. throw new Error("WebGL not supported");
  11571. }
  11572. this._onCanvasFocus = function () {
  11573. _this.onCanvasFocusObservable.notifyObservers(_this);
  11574. };
  11575. this._onCanvasBlur = function () {
  11576. _this.onCanvasBlurObservable.notifyObservers(_this);
  11577. };
  11578. canvas.addEventListener("focus", this._onCanvasFocus);
  11579. canvas.addEventListener("blur", this._onCanvasBlur);
  11580. this._onBlur = function () {
  11581. if (_this.disablePerformanceMonitorInBackground) {
  11582. _this._performanceMonitor.disable();
  11583. }
  11584. _this._windowIsBackground = true;
  11585. };
  11586. this._onFocus = function () {
  11587. if (_this.disablePerformanceMonitorInBackground) {
  11588. _this._performanceMonitor.enable();
  11589. }
  11590. _this._windowIsBackground = false;
  11591. };
  11592. this._onCanvasPointerOut = function (ev) {
  11593. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11594. };
  11595. window.addEventListener("blur", this._onBlur);
  11596. window.addEventListener("focus", this._onFocus);
  11597. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11598. // Context lost
  11599. if (!this._doNotHandleContextLost) {
  11600. this._onContextLost = function (evt) {
  11601. evt.preventDefault();
  11602. _this._contextWasLost = true;
  11603. BABYLON.Tools.Warn("WebGL context lost.");
  11604. _this.onContextLostObservable.notifyObservers(_this);
  11605. };
  11606. this._onContextRestored = function (evt) {
  11607. // Adding a timeout to avoid race condition at browser level
  11608. setTimeout(function () {
  11609. // Rebuild gl context
  11610. _this._initGLContext();
  11611. // Rebuild effects
  11612. _this._rebuildEffects();
  11613. // Rebuild textures
  11614. _this._rebuildInternalTextures();
  11615. // Rebuild buffers
  11616. _this._rebuildBuffers();
  11617. // Cache
  11618. _this.wipeCaches(true);
  11619. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11620. _this.onContextRestoredObservable.notifyObservers(_this);
  11621. _this._contextWasLost = false;
  11622. }, 0);
  11623. };
  11624. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11625. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11626. }
  11627. }
  11628. else {
  11629. this._gl = canvasOrContext;
  11630. this._renderingCanvas = this._gl.canvas;
  11631. if (this._gl.renderbufferStorageMultisample) {
  11632. this._webGLVersion = 2.0;
  11633. }
  11634. options.stencil = this._gl.getContextAttributes().stencil;
  11635. }
  11636. // Viewport
  11637. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11638. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11639. this.resize();
  11640. this._isStencilEnable = options.stencil ? true : false;
  11641. this._initGLContext();
  11642. if (canvas) {
  11643. // Fullscreen
  11644. this._onFullscreenChange = function () {
  11645. if (document.fullscreen !== undefined) {
  11646. _this.isFullscreen = document.fullscreen;
  11647. }
  11648. else if (document.mozFullScreen !== undefined) {
  11649. _this.isFullscreen = document.mozFullScreen;
  11650. }
  11651. else if (document.webkitIsFullScreen !== undefined) {
  11652. _this.isFullscreen = document.webkitIsFullScreen;
  11653. }
  11654. else if (document.msIsFullScreen !== undefined) {
  11655. _this.isFullscreen = document.msIsFullScreen;
  11656. }
  11657. // Pointer lock
  11658. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11659. canvas.requestPointerLock = canvas.requestPointerLock ||
  11660. canvas.msRequestPointerLock ||
  11661. canvas.mozRequestPointerLock ||
  11662. canvas.webkitRequestPointerLock;
  11663. if (canvas.requestPointerLock) {
  11664. canvas.requestPointerLock();
  11665. }
  11666. }
  11667. };
  11668. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11669. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11670. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11671. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11672. // Pointer lock
  11673. this._onPointerLockChange = function () {
  11674. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11675. document.webkitPointerLockElement === canvas ||
  11676. document.msPointerLockElement === canvas ||
  11677. document.pointerLockElement === canvas);
  11678. };
  11679. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11680. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11681. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11682. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11683. this._onVRDisplayPointerRestricted = function () {
  11684. if (canvas) {
  11685. canvas.requestPointerLock();
  11686. }
  11687. };
  11688. this._onVRDisplayPointerUnrestricted = function () {
  11689. document.exitPointerLock();
  11690. };
  11691. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11692. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11693. }
  11694. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11695. Engine.audioEngine = new BABYLON.AudioEngine();
  11696. }
  11697. // Prepare buffer pointers
  11698. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11699. this._currentBufferPointers[i] = new BufferPointer();
  11700. }
  11701. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11702. // Load WebVR Devices
  11703. if (options.autoEnableWebVR) {
  11704. this.initWebVR();
  11705. }
  11706. // Detect if we are running on a faulty buggy OS.
  11707. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11708. // Detect if we are running on a faulty buggy desktop OS.
  11709. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11710. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11711. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11712. }
  11713. Object.defineProperty(Engine, "LastCreatedEngine", {
  11714. /**
  11715. * Gets the latest created engine
  11716. */
  11717. get: function () {
  11718. if (Engine.Instances.length === 0) {
  11719. return null;
  11720. }
  11721. return Engine.Instances[Engine.Instances.length - 1];
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Engine, "LastCreatedScene", {
  11727. /**
  11728. * Gets the latest created scene
  11729. */
  11730. get: function () {
  11731. var lastCreatedEngine = Engine.LastCreatedEngine;
  11732. if (!lastCreatedEngine) {
  11733. return null;
  11734. }
  11735. if (lastCreatedEngine.scenes.length === 0) {
  11736. return null;
  11737. }
  11738. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. /**
  11744. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11745. * @param flag defines which part of the materials must be marked as dirty
  11746. * @param predicate defines a predicate used to filter which materials should be affected
  11747. */
  11748. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11749. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11750. var engine = Engine.Instances[engineIndex];
  11751. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11752. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11753. }
  11754. }
  11755. };
  11756. Object.defineProperty(Engine, "Version", {
  11757. /**
  11758. * Returns the current version of the framework
  11759. */
  11760. get: function () {
  11761. return "3.3.0-beta.5";
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11767. /**
  11768. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11769. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11770. */
  11771. get: function () {
  11772. return this._vrExclusivePointerMode;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11778. /**
  11779. * Gets a boolean indicating that the engine supports uniform buffers
  11780. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11781. */
  11782. get: function () {
  11783. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11789. /**
  11790. * Gets a boolean indicating that only power of 2 textures are supported
  11791. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11792. */
  11793. get: function () {
  11794. return this._webGLVersion < 2 || this.forcePOTTextures;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11800. /**
  11801. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11802. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11803. */
  11804. get: function () {
  11805. return this._doNotHandleContextLost;
  11806. },
  11807. set: function (value) {
  11808. this._doNotHandleContextLost = value;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11814. /**
  11815. * Gets the performance monitor attached to this engine
  11816. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11817. */
  11818. get: function () {
  11819. return this._performanceMonitor;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11825. /**
  11826. * Gets the list of texture formats supported
  11827. */
  11828. get: function () {
  11829. return this._texturesSupported;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11835. /**
  11836. * Gets the list of texture formats in use
  11837. */
  11838. get: function () {
  11839. return this._textureFormatInUse;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "currentViewport", {
  11845. /**
  11846. * Gets the current viewport
  11847. */
  11848. get: function () {
  11849. return this._cachedViewport;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11855. /**
  11856. * Gets the default empty texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyTexture) {
  11860. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11861. }
  11862. return this._emptyTexture;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11868. /**
  11869. * Gets the default empty 3D texture
  11870. */
  11871. get: function () {
  11872. if (!this._emptyTexture3D) {
  11873. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11874. }
  11875. return this._emptyTexture3D;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11881. /**
  11882. * Gets the default empty cube texture
  11883. */
  11884. get: function () {
  11885. if (!this._emptyCubeTexture) {
  11886. var faceData = new Uint8Array(4);
  11887. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11888. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11889. }
  11890. return this._emptyCubeTexture;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Engine.prototype._rebuildInternalTextures = function () {
  11896. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11897. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11898. var internalTexture = currentState_1[_i];
  11899. internalTexture._rebuild();
  11900. }
  11901. };
  11902. Engine.prototype._rebuildEffects = function () {
  11903. for (var key in this._compiledEffects) {
  11904. var effect = this._compiledEffects[key];
  11905. effect._prepareEffect();
  11906. }
  11907. BABYLON.Effect.ResetCache();
  11908. };
  11909. Engine.prototype._rebuildBuffers = function () {
  11910. // Index / Vertex
  11911. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11912. var scene = _a[_i];
  11913. scene.resetCachedMaterial();
  11914. scene._rebuildGeometries();
  11915. scene._rebuildTextures();
  11916. }
  11917. // Uniforms
  11918. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11919. var uniformBuffer = _c[_b];
  11920. uniformBuffer._rebuild();
  11921. }
  11922. };
  11923. Engine.prototype._initGLContext = function () {
  11924. // Caps
  11925. this._caps = new EngineCapabilities();
  11926. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11927. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11928. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11929. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11930. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11931. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11932. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11933. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11934. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11935. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11936. // Infos
  11937. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11938. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11939. if (rendererInfo != null) {
  11940. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11941. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11942. }
  11943. if (!this._glVendor) {
  11944. this._glVendor = "Unknown vendor";
  11945. }
  11946. if (!this._glRenderer) {
  11947. this._glRenderer = "Unknown renderer";
  11948. }
  11949. // Constants
  11950. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11951. if (this._gl.RGBA16F !== 0x881A) {
  11952. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11953. }
  11954. if (this._gl.RGBA32F !== 0x8814) {
  11955. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11956. }
  11957. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11958. this._gl.DEPTH24_STENCIL8 = 35056;
  11959. }
  11960. // Extensions
  11961. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11962. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11963. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11964. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11965. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11966. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11967. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11968. 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');
  11969. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11970. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11971. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11972. this._caps.highPrecisionShaderSupported = true;
  11973. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11974. if (this._caps.timerQuery) {
  11975. if (this._webGLVersion === 1) {
  11976. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11977. }
  11978. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11979. }
  11980. // Checks if some of the format renders first to allow the use of webgl inspector.
  11981. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11982. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11983. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11984. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11985. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11986. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11987. if (this._webGLVersion > 1) {
  11988. this._gl.HALF_FLOAT_OES = 0x140B;
  11989. }
  11990. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11991. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11992. // Draw buffers
  11993. if (this._webGLVersion > 1) {
  11994. this._caps.drawBuffersExtension = true;
  11995. }
  11996. else {
  11997. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11998. if (drawBuffersExtension !== null) {
  11999. this._caps.drawBuffersExtension = true;
  12000. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12001. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12002. for (var i = 0; i < 16; i++) {
  12003. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12004. }
  12005. }
  12006. else {
  12007. this._caps.drawBuffersExtension = false;
  12008. }
  12009. }
  12010. // Depth Texture
  12011. if (this._webGLVersion > 1) {
  12012. this._caps.depthTextureExtension = true;
  12013. }
  12014. else {
  12015. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12016. if (depthTextureExtension != null) {
  12017. this._caps.depthTextureExtension = true;
  12018. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12019. }
  12020. }
  12021. // Vertex array object
  12022. if (this._webGLVersion > 1) {
  12023. this._caps.vertexArrayObject = true;
  12024. }
  12025. else {
  12026. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12027. if (vertexArrayObjectExtension != null) {
  12028. this._caps.vertexArrayObject = true;
  12029. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12030. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12031. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12032. }
  12033. else {
  12034. this._caps.vertexArrayObject = false;
  12035. }
  12036. }
  12037. // Instances count
  12038. if (this._webGLVersion > 1) {
  12039. this._caps.instancedArrays = true;
  12040. }
  12041. else {
  12042. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12043. if (instanceExtension != null) {
  12044. this._caps.instancedArrays = true;
  12045. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12046. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12047. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12048. }
  12049. else {
  12050. this._caps.instancedArrays = false;
  12051. }
  12052. }
  12053. // Intelligently add supported compressed formats in order to check for.
  12054. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12055. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12056. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12057. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12058. if (this._caps.astc)
  12059. this.texturesSupported.push('-astc.ktx');
  12060. if (this._caps.s3tc)
  12061. this.texturesSupported.push('-dxt.ktx');
  12062. if (this._caps.pvrtc)
  12063. this.texturesSupported.push('-pvrtc.ktx');
  12064. if (this._caps.etc2)
  12065. this.texturesSupported.push('-etc2.ktx');
  12066. if (this._caps.etc1)
  12067. this.texturesSupported.push('-etc1.ktx');
  12068. if (this._gl.getShaderPrecisionFormat) {
  12069. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12070. if (highp) {
  12071. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12072. }
  12073. }
  12074. // Depth buffer
  12075. this.setDepthBuffer(true);
  12076. this.setDepthFunctionToLessOrEqual();
  12077. this.setDepthWrite(true);
  12078. // Texture maps
  12079. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12080. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12081. this._nextFreeTextureSlots.push(slot);
  12082. }
  12083. };
  12084. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12085. /**
  12086. * Gets version of the current webGL context
  12087. */
  12088. get: function () {
  12089. return this._webGLVersion;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12095. /**
  12096. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12097. */
  12098. get: function () {
  12099. return this._isStencilEnable;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Engine.prototype._prepareWorkingCanvas = function () {
  12105. if (this._workingCanvas) {
  12106. return;
  12107. }
  12108. this._workingCanvas = document.createElement("canvas");
  12109. var context = this._workingCanvas.getContext("2d");
  12110. if (context) {
  12111. this._workingContext = context;
  12112. }
  12113. };
  12114. /**
  12115. * Reset the texture cache to empty state
  12116. */
  12117. Engine.prototype.resetTextureCache = function () {
  12118. for (var key in this._boundTexturesCache) {
  12119. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12120. continue;
  12121. }
  12122. var boundTexture = this._boundTexturesCache[key];
  12123. if (boundTexture) {
  12124. this._removeDesignatedSlot(boundTexture);
  12125. }
  12126. this._boundTexturesCache[key] = null;
  12127. }
  12128. if (!this.disableTextureBindingOptimization) {
  12129. this._nextFreeTextureSlots = [];
  12130. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12131. this._nextFreeTextureSlots.push(slot);
  12132. }
  12133. }
  12134. this._currentTextureChannel = -1;
  12135. };
  12136. /**
  12137. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12138. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12139. * @returns true if engine is in deterministic lock step mode
  12140. */
  12141. Engine.prototype.isDeterministicLockStep = function () {
  12142. return this._deterministicLockstep;
  12143. };
  12144. /**
  12145. * Gets the max steps when engine is running in deterministic lock step
  12146. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12147. * @returns the max steps
  12148. */
  12149. Engine.prototype.getLockstepMaxSteps = function () {
  12150. return this._lockstepMaxSteps;
  12151. };
  12152. /**
  12153. * Gets an object containing information about the current webGL context
  12154. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12155. */
  12156. Engine.prototype.getGlInfo = function () {
  12157. return {
  12158. vendor: this._glVendor,
  12159. renderer: this._glRenderer,
  12160. version: this._glVersion
  12161. };
  12162. };
  12163. /**
  12164. * Gets current aspect ratio
  12165. * @param camera defines the camera to use to get the aspect ratio
  12166. * @param useScreen defines if screen size must be used (or the current render target if any)
  12167. * @returns a number defining the aspect ratio
  12168. */
  12169. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12170. if (useScreen === void 0) { useScreen = false; }
  12171. var viewport = camera.viewport;
  12172. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12173. };
  12174. /**
  12175. * Gets current screen aspect ratio
  12176. * @returns a number defining the aspect ratio
  12177. */
  12178. Engine.prototype.getScreenAspectRatio = function () {
  12179. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12180. };
  12181. /**
  12182. * Gets the current render width
  12183. * @param useScreen defines if screen size must be used (or the current render target if any)
  12184. * @returns a number defining the current render width
  12185. */
  12186. Engine.prototype.getRenderWidth = function (useScreen) {
  12187. if (useScreen === void 0) { useScreen = false; }
  12188. if (!useScreen && this._currentRenderTarget) {
  12189. return this._currentRenderTarget.width;
  12190. }
  12191. return this._gl.drawingBufferWidth;
  12192. };
  12193. /**
  12194. * Gets the current render height
  12195. * @param useScreen defines if screen size must be used (or the current render target if any)
  12196. * @returns a number defining the current render height
  12197. */
  12198. Engine.prototype.getRenderHeight = function (useScreen) {
  12199. if (useScreen === void 0) { useScreen = false; }
  12200. if (!useScreen && this._currentRenderTarget) {
  12201. return this._currentRenderTarget.height;
  12202. }
  12203. return this._gl.drawingBufferHeight;
  12204. };
  12205. /**
  12206. * Gets the HTML canvas attached with the current webGL context
  12207. * @returns a HTML canvas
  12208. */
  12209. Engine.prototype.getRenderingCanvas = function () {
  12210. return this._renderingCanvas;
  12211. };
  12212. /**
  12213. * Gets the client rect of the HTML canvas attached with the current webGL context
  12214. * @returns a client rectanglee
  12215. */
  12216. Engine.prototype.getRenderingCanvasClientRect = function () {
  12217. if (!this._renderingCanvas) {
  12218. return null;
  12219. }
  12220. return this._renderingCanvas.getBoundingClientRect();
  12221. };
  12222. /**
  12223. * Defines the hardware scaling level.
  12224. * By default the hardware scaling level is computed from the window device ratio.
  12225. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12226. * @param level defines the level to use
  12227. */
  12228. Engine.prototype.setHardwareScalingLevel = function (level) {
  12229. this._hardwareScalingLevel = level;
  12230. this.resize();
  12231. };
  12232. /**
  12233. * Gets the current hardware scaling level.
  12234. * By default the hardware scaling level is computed from the window device ratio.
  12235. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12236. * @returns a number indicating the current hardware scaling level
  12237. */
  12238. Engine.prototype.getHardwareScalingLevel = function () {
  12239. return this._hardwareScalingLevel;
  12240. };
  12241. /**
  12242. * Gets the list of loaded textures
  12243. * @returns an array containing all loaded textures
  12244. */
  12245. Engine.prototype.getLoadedTexturesCache = function () {
  12246. return this._internalTexturesCache;
  12247. };
  12248. /**
  12249. * Gets the object containing all engine capabilities
  12250. * @returns the EngineCapabilities object
  12251. */
  12252. Engine.prototype.getCaps = function () {
  12253. return this._caps;
  12254. };
  12255. Object.defineProperty(Engine.prototype, "drawCalls", {
  12256. /** @hidden */
  12257. get: function () {
  12258. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12259. return 0;
  12260. },
  12261. enumerable: true,
  12262. configurable: true
  12263. });
  12264. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12265. /** @hidden */
  12266. get: function () {
  12267. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12268. return null;
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. /**
  12274. * Gets the current depth function
  12275. * @returns a number defining the depth function
  12276. */
  12277. Engine.prototype.getDepthFunction = function () {
  12278. return this._depthCullingState.depthFunc;
  12279. };
  12280. /**
  12281. * Sets the current depth function
  12282. * @param depthFunc defines the function to use
  12283. */
  12284. Engine.prototype.setDepthFunction = function (depthFunc) {
  12285. this._depthCullingState.depthFunc = depthFunc;
  12286. };
  12287. /**
  12288. * Sets the current depth function to GREATER
  12289. */
  12290. Engine.prototype.setDepthFunctionToGreater = function () {
  12291. this._depthCullingState.depthFunc = this._gl.GREATER;
  12292. };
  12293. /**
  12294. * Sets the current depth function to GEQUAL
  12295. */
  12296. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12297. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12298. };
  12299. /**
  12300. * Sets the current depth function to LESS
  12301. */
  12302. Engine.prototype.setDepthFunctionToLess = function () {
  12303. this._depthCullingState.depthFunc = this._gl.LESS;
  12304. };
  12305. /**
  12306. * Sets the current depth function to LEQUAL
  12307. */
  12308. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12309. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12310. };
  12311. /**
  12312. * Gets a boolean indicating if stencil buffer is enabled
  12313. * @returns the current stencil buffer state
  12314. */
  12315. Engine.prototype.getStencilBuffer = function () {
  12316. return this._stencilState.stencilTest;
  12317. };
  12318. /**
  12319. * Enable or disable the stencil buffer
  12320. * @param enable defines if the stencil buffer must be enabled or disabled
  12321. */
  12322. Engine.prototype.setStencilBuffer = function (enable) {
  12323. this._stencilState.stencilTest = enable;
  12324. };
  12325. /**
  12326. * Gets the current stencil mask
  12327. * @returns a number defining the new stencil mask to use
  12328. */
  12329. Engine.prototype.getStencilMask = function () {
  12330. return this._stencilState.stencilMask;
  12331. };
  12332. /**
  12333. * Sets the current stencil mask
  12334. * @param mask defines the new stencil mask to use
  12335. */
  12336. Engine.prototype.setStencilMask = function (mask) {
  12337. this._stencilState.stencilMask = mask;
  12338. };
  12339. /**
  12340. * Gets the current stencil function
  12341. * @returns a number defining the stencil function to use
  12342. */
  12343. Engine.prototype.getStencilFunction = function () {
  12344. return this._stencilState.stencilFunc;
  12345. };
  12346. /**
  12347. * Gets the current stencil reference value
  12348. * @returns a number defining the stencil reference value to use
  12349. */
  12350. Engine.prototype.getStencilFunctionReference = function () {
  12351. return this._stencilState.stencilFuncRef;
  12352. };
  12353. /**
  12354. * Gets the current stencil mask
  12355. * @returns a number defining the stencil mask to use
  12356. */
  12357. Engine.prototype.getStencilFunctionMask = function () {
  12358. return this._stencilState.stencilFuncMask;
  12359. };
  12360. /**
  12361. * Sets the current stencil function
  12362. * @param stencilFunc defines the new stencil function to use
  12363. */
  12364. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12365. this._stencilState.stencilFunc = stencilFunc;
  12366. };
  12367. /**
  12368. * Sets the current stencil reference
  12369. * @param reference defines the new stencil reference to use
  12370. */
  12371. Engine.prototype.setStencilFunctionReference = function (reference) {
  12372. this._stencilState.stencilFuncRef = reference;
  12373. };
  12374. /**
  12375. * Sets the current stencil mask
  12376. * @param mask defines the new stencil mask to use
  12377. */
  12378. Engine.prototype.setStencilFunctionMask = function (mask) {
  12379. this._stencilState.stencilFuncMask = mask;
  12380. };
  12381. /**
  12382. * Gets the current stencil operation when stencil fails
  12383. * @returns a number defining stencil operation to use when stencil fails
  12384. */
  12385. Engine.prototype.getStencilOperationFail = function () {
  12386. return this._stencilState.stencilOpStencilFail;
  12387. };
  12388. /**
  12389. * Gets the current stencil operation when depth fails
  12390. * @returns a number defining stencil operation to use when depth fails
  12391. */
  12392. Engine.prototype.getStencilOperationDepthFail = function () {
  12393. return this._stencilState.stencilOpDepthFail;
  12394. };
  12395. /**
  12396. * Gets the current stencil operation when stencil passes
  12397. * @returns a number defining stencil operation to use when stencil passes
  12398. */
  12399. Engine.prototype.getStencilOperationPass = function () {
  12400. return this._stencilState.stencilOpStencilDepthPass;
  12401. };
  12402. /**
  12403. * Sets the stencil operation to use when stencil fails
  12404. * @param operation defines the stencil operation to use when stencil fails
  12405. */
  12406. Engine.prototype.setStencilOperationFail = function (operation) {
  12407. this._stencilState.stencilOpStencilFail = operation;
  12408. };
  12409. /**
  12410. * Sets the stencil operation to use when depth fails
  12411. * @param operation defines the stencil operation to use when depth fails
  12412. */
  12413. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12414. this._stencilState.stencilOpDepthFail = operation;
  12415. };
  12416. /**
  12417. * Sets the stencil operation to use when stencil passes
  12418. * @param operation defines the stencil operation to use when stencil passes
  12419. */
  12420. Engine.prototype.setStencilOperationPass = function (operation) {
  12421. this._stencilState.stencilOpStencilDepthPass = operation;
  12422. };
  12423. /**
  12424. * Sets a boolean indicating if the dithering state is enabled or disabled
  12425. * @param value defines the dithering state
  12426. */
  12427. Engine.prototype.setDitheringState = function (value) {
  12428. if (value) {
  12429. this._gl.enable(this._gl.DITHER);
  12430. }
  12431. else {
  12432. this._gl.disable(this._gl.DITHER);
  12433. }
  12434. };
  12435. /**
  12436. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12437. * @param value defines the rasterizer state
  12438. */
  12439. Engine.prototype.setRasterizerState = function (value) {
  12440. if (value) {
  12441. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12442. }
  12443. else {
  12444. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12445. }
  12446. };
  12447. /**
  12448. * stop executing a render loop function and remove it from the execution array
  12449. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12450. */
  12451. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12452. if (!renderFunction) {
  12453. this._activeRenderLoops = [];
  12454. return;
  12455. }
  12456. var index = this._activeRenderLoops.indexOf(renderFunction);
  12457. if (index >= 0) {
  12458. this._activeRenderLoops.splice(index, 1);
  12459. }
  12460. };
  12461. /** @hidden */
  12462. Engine.prototype._renderLoop = function () {
  12463. if (!this._contextWasLost) {
  12464. var shouldRender = true;
  12465. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12466. shouldRender = false;
  12467. }
  12468. if (shouldRender) {
  12469. // Start new frame
  12470. this.beginFrame();
  12471. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12472. var renderFunction = this._activeRenderLoops[index];
  12473. renderFunction();
  12474. }
  12475. // Present
  12476. this.endFrame();
  12477. }
  12478. }
  12479. if (this._activeRenderLoops.length > 0) {
  12480. // Register new frame
  12481. var requester = null;
  12482. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12483. requester = this._vrDisplay;
  12484. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12485. }
  12486. else {
  12487. this._renderingQueueLaunched = false;
  12488. }
  12489. };
  12490. /**
  12491. * Register and execute a render loop. The engine can have more than one render function
  12492. * @param renderFunction defines the function to continuously execute
  12493. */
  12494. Engine.prototype.runRenderLoop = function (renderFunction) {
  12495. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12496. return;
  12497. }
  12498. this._activeRenderLoops.push(renderFunction);
  12499. if (!this._renderingQueueLaunched) {
  12500. this._renderingQueueLaunched = true;
  12501. this._bindedRenderFunction = this._renderLoop.bind(this);
  12502. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12503. }
  12504. };
  12505. /**
  12506. * Toggle full screen mode
  12507. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12508. * @param options defines an option object to be sent to the requestFullscreen function
  12509. */
  12510. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12511. if (this.isFullscreen) {
  12512. BABYLON.Tools.ExitFullscreen();
  12513. }
  12514. else {
  12515. this._pointerLockRequested = requestPointerLock;
  12516. if (this._renderingCanvas) {
  12517. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12518. }
  12519. }
  12520. };
  12521. /**
  12522. * Clear the current render buffer or the current render target (if any is set up)
  12523. * @param color defines the color to use
  12524. * @param backBuffer defines if the back buffer must be cleared
  12525. * @param depth defines if the depth buffer must be cleared
  12526. * @param stencil defines if the stencil buffer must be cleared
  12527. */
  12528. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12529. if (stencil === void 0) { stencil = false; }
  12530. this.applyStates();
  12531. var mode = 0;
  12532. if (backBuffer && color) {
  12533. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12534. mode |= this._gl.COLOR_BUFFER_BIT;
  12535. }
  12536. if (depth) {
  12537. this._gl.clearDepth(1.0);
  12538. mode |= this._gl.DEPTH_BUFFER_BIT;
  12539. }
  12540. if (stencil) {
  12541. this._gl.clearStencil(0);
  12542. mode |= this._gl.STENCIL_BUFFER_BIT;
  12543. }
  12544. this._gl.clear(mode);
  12545. };
  12546. /**
  12547. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12548. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12549. * @param y defines the y-coordinate of the corner of the clear rectangle
  12550. * @param width defines the width of the clear rectangle
  12551. * @param height defines the height of the clear rectangle
  12552. * @param clearColor defines the clear color
  12553. */
  12554. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12555. var gl = this._gl;
  12556. // Save state
  12557. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12558. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12559. // Change state
  12560. gl.enable(gl.SCISSOR_TEST);
  12561. gl.scissor(x, y, width, height);
  12562. // Clear
  12563. this.clear(clearColor, true, true, true);
  12564. // Restore state
  12565. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12566. if (curScissor === true) {
  12567. gl.enable(gl.SCISSOR_TEST);
  12568. }
  12569. else {
  12570. gl.disable(gl.SCISSOR_TEST);
  12571. }
  12572. };
  12573. /** @hidden */
  12574. Engine.prototype._viewport = function (x, y, width, height) {
  12575. if (x !== this._viewportCached.x ||
  12576. y !== this._viewportCached.y ||
  12577. width !== this._viewportCached.z ||
  12578. height !== this._viewportCached.w) {
  12579. this._viewportCached.x = x;
  12580. this._viewportCached.y = y;
  12581. this._viewportCached.z = width;
  12582. this._viewportCached.w = height;
  12583. this._gl.viewport(x, y, width, height);
  12584. }
  12585. };
  12586. /**
  12587. * Set the WebGL's viewport
  12588. * @param viewport defines the viewport element to be used
  12589. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12590. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12591. */
  12592. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12593. var width = requiredWidth || this.getRenderWidth();
  12594. var height = requiredHeight || this.getRenderHeight();
  12595. var x = viewport.x || 0;
  12596. var y = viewport.y || 0;
  12597. this._cachedViewport = viewport;
  12598. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12599. };
  12600. /**
  12601. * Directly set the WebGL Viewport
  12602. * @param x defines the x coordinate of the viewport (in screen space)
  12603. * @param y defines the y coordinate of the viewport (in screen space)
  12604. * @param width defines the width of the viewport (in screen space)
  12605. * @param height defines the height of the viewport (in screen space)
  12606. * @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
  12607. */
  12608. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12609. var currentViewport = this._cachedViewport;
  12610. this._cachedViewport = null;
  12611. this._viewport(x, y, width, height);
  12612. return currentViewport;
  12613. };
  12614. /**
  12615. * Begin a new frame
  12616. */
  12617. Engine.prototype.beginFrame = function () {
  12618. this.onBeginFrameObservable.notifyObservers(this);
  12619. this._measureFps();
  12620. };
  12621. /**
  12622. * Enf the current frame
  12623. */
  12624. Engine.prototype.endFrame = function () {
  12625. // Force a flush in case we are using a bad OS.
  12626. if (this._badOS) {
  12627. this.flushFramebuffer();
  12628. }
  12629. // Submit frame to the vr device, if enabled
  12630. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12631. // TODO: We should only submit the frame if we read frameData successfully.
  12632. this._vrDisplay.submitFrame();
  12633. }
  12634. this.onEndFrameObservable.notifyObservers(this);
  12635. };
  12636. /**
  12637. * Resize the view according to the canvas' size
  12638. */
  12639. Engine.prototype.resize = function () {
  12640. // We're not resizing the size of the canvas while in VR mode & presenting
  12641. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12642. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12643. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12644. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12645. }
  12646. };
  12647. /**
  12648. * Force a specific size of the canvas
  12649. * @param width defines the new canvas' width
  12650. * @param height defines the new canvas' height
  12651. */
  12652. Engine.prototype.setSize = function (width, height) {
  12653. if (!this._renderingCanvas) {
  12654. return;
  12655. }
  12656. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12657. return;
  12658. }
  12659. this._renderingCanvas.width = width;
  12660. this._renderingCanvas.height = height;
  12661. for (var index = 0; index < this.scenes.length; index++) {
  12662. var scene = this.scenes[index];
  12663. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12664. var cam = scene.cameras[camIndex];
  12665. cam._currentRenderId = 0;
  12666. }
  12667. }
  12668. if (this.onResizeObservable.hasObservers) {
  12669. this.onResizeObservable.notifyObservers(this);
  12670. }
  12671. };
  12672. // WebVR functions
  12673. /**
  12674. * Gets a boolean indicating if a webVR device was detected
  12675. * @returns true if a webVR device was detected
  12676. */
  12677. Engine.prototype.isVRDevicePresent = function () {
  12678. return !!this._vrDisplay;
  12679. };
  12680. /**
  12681. * Gets the current webVR device
  12682. * @returns the current webVR device (or null)
  12683. */
  12684. Engine.prototype.getVRDevice = function () {
  12685. return this._vrDisplay;
  12686. };
  12687. /**
  12688. * Initializes a webVR display and starts listening to display change events
  12689. * The onVRDisplayChangedObservable will be notified upon these changes
  12690. * @returns The onVRDisplayChangedObservable
  12691. */
  12692. Engine.prototype.initWebVR = function () {
  12693. this.initWebVRAsync();
  12694. return this.onVRDisplayChangedObservable;
  12695. };
  12696. /**
  12697. * Initializes a webVR display and starts listening to display change events
  12698. * The onVRDisplayChangedObservable will be notified upon these changes
  12699. * @returns A promise containing a VRDisplay and if vr is supported
  12700. */
  12701. Engine.prototype.initWebVRAsync = function () {
  12702. var _this = this;
  12703. var notifyObservers = function () {
  12704. var eventArgs = {
  12705. vrDisplay: _this._vrDisplay,
  12706. vrSupported: _this._vrSupported
  12707. };
  12708. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12709. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12710. };
  12711. if (!this._onVrDisplayConnect) {
  12712. this._onVrDisplayConnect = function (event) {
  12713. _this._vrDisplay = event.display;
  12714. notifyObservers();
  12715. };
  12716. this._onVrDisplayDisconnect = function () {
  12717. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12718. _this._vrDisplay = undefined;
  12719. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12720. notifyObservers();
  12721. };
  12722. this._onVrDisplayPresentChange = function () {
  12723. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12724. };
  12725. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12726. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12727. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12728. }
  12729. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12730. this._webVRInitPromise.then(notifyObservers);
  12731. return this._webVRInitPromise;
  12732. };
  12733. /**
  12734. * Call this function to switch to webVR mode
  12735. * Will do nothing if webVR is not supported or if there is no webVR device
  12736. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12737. */
  12738. Engine.prototype.enableVR = function () {
  12739. var _this = this;
  12740. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12741. var onResolved = function () {
  12742. _this.onVRRequestPresentComplete.notifyObservers(true);
  12743. _this._onVRFullScreenTriggered();
  12744. };
  12745. var onRejected = function () {
  12746. _this.onVRRequestPresentComplete.notifyObservers(false);
  12747. };
  12748. this.onVRRequestPresentStart.notifyObservers(this);
  12749. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12750. }
  12751. };
  12752. /**
  12753. * Call this function to leave webVR mode
  12754. * Will do nothing if webVR is not supported or if there is no webVR device
  12755. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12756. */
  12757. Engine.prototype.disableVR = function () {
  12758. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12759. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12760. }
  12761. };
  12762. Engine.prototype._getVRDisplaysAsync = function () {
  12763. var _this = this;
  12764. return new Promise(function (res, rej) {
  12765. if (navigator.getVRDisplays) {
  12766. navigator.getVRDisplays().then(function (devices) {
  12767. _this._vrSupported = true;
  12768. // note that devices may actually be an empty array. This is fine;
  12769. // we expect this._vrDisplay to be undefined in this case.
  12770. _this._vrDisplay = devices[0];
  12771. res({
  12772. vrDisplay: _this._vrDisplay,
  12773. vrSupported: _this._vrSupported
  12774. });
  12775. });
  12776. }
  12777. else {
  12778. _this._vrDisplay = undefined;
  12779. _this._vrSupported = false;
  12780. res({
  12781. vrDisplay: _this._vrDisplay,
  12782. vrSupported: _this._vrSupported
  12783. });
  12784. }
  12785. });
  12786. };
  12787. /**
  12788. * Binds the frame buffer to the specified texture.
  12789. * @param texture The texture to render to or null for the default canvas
  12790. * @param faceIndex The face of the texture to render to in case of cube texture
  12791. * @param requiredWidth The width of the target to render to
  12792. * @param requiredHeight The height of the target to render to
  12793. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12794. * @param depthStencilTexture The depth stencil texture to use to render
  12795. * @param lodLevel defines le lod level to bind to the frame buffer
  12796. */
  12797. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12798. if (lodLevel === void 0) { lodLevel = 0; }
  12799. if (this._currentRenderTarget) {
  12800. this.unBindFramebuffer(this._currentRenderTarget);
  12801. }
  12802. this._currentRenderTarget = texture;
  12803. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12804. var gl = this._gl;
  12805. if (texture.isCube) {
  12806. if (faceIndex === undefined) {
  12807. faceIndex = 0;
  12808. }
  12809. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12810. if (depthStencilTexture) {
  12811. if (depthStencilTexture._generateStencilBuffer) {
  12812. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12813. }
  12814. else {
  12815. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12816. }
  12817. }
  12818. }
  12819. if (this._cachedViewport && !forceFullscreenViewport) {
  12820. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12821. }
  12822. else {
  12823. if (!requiredWidth) {
  12824. requiredWidth = texture.width;
  12825. if (lodLevel) {
  12826. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12827. }
  12828. }
  12829. if (!requiredHeight) {
  12830. requiredHeight = texture.height;
  12831. if (lodLevel) {
  12832. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12833. }
  12834. }
  12835. this._viewport(0, 0, requiredWidth, requiredHeight);
  12836. }
  12837. this.wipeCaches();
  12838. };
  12839. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12840. if (this._currentFramebuffer !== framebuffer) {
  12841. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12842. this._currentFramebuffer = framebuffer;
  12843. }
  12844. };
  12845. /**
  12846. * Unbind the current render target texture from the webGL context
  12847. * @param texture defines the render target texture to unbind
  12848. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12849. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12850. */
  12851. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12852. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12853. this._currentRenderTarget = null;
  12854. // If MSAA, we need to bitblt back to main texture
  12855. var gl = this._gl;
  12856. if (texture._MSAAFramebuffer) {
  12857. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12858. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12859. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12860. }
  12861. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12862. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12863. gl.generateMipmap(gl.TEXTURE_2D);
  12864. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12865. }
  12866. if (onBeforeUnbind) {
  12867. if (texture._MSAAFramebuffer) {
  12868. // Bind the correct framebuffer
  12869. this.bindUnboundFramebuffer(texture._framebuffer);
  12870. }
  12871. onBeforeUnbind();
  12872. }
  12873. this.bindUnboundFramebuffer(null);
  12874. };
  12875. /**
  12876. * Unbind a list of render target textures from the webGL context
  12877. * This is used only when drawBuffer extension or webGL2 are active
  12878. * @param textures defines the render target textures to unbind
  12879. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12880. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12881. */
  12882. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12883. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12884. this._currentRenderTarget = null;
  12885. // If MSAA, we need to bitblt back to main texture
  12886. var gl = this._gl;
  12887. if (textures[0]._MSAAFramebuffer) {
  12888. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12889. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12890. var attachments = textures[0]._attachments;
  12891. if (!attachments) {
  12892. attachments = new Array(textures.length);
  12893. textures[0]._attachments = attachments;
  12894. }
  12895. for (var i = 0; i < textures.length; i++) {
  12896. var texture = textures[i];
  12897. for (var j = 0; j < attachments.length; j++) {
  12898. attachments[j] = gl.NONE;
  12899. }
  12900. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12901. gl.readBuffer(attachments[i]);
  12902. gl.drawBuffers(attachments);
  12903. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12904. }
  12905. for (var i = 0; i < attachments.length; i++) {
  12906. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12907. }
  12908. gl.drawBuffers(attachments);
  12909. }
  12910. for (var i = 0; i < textures.length; i++) {
  12911. var texture = textures[i];
  12912. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12913. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12914. gl.generateMipmap(gl.TEXTURE_2D);
  12915. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12916. }
  12917. }
  12918. if (onBeforeUnbind) {
  12919. if (textures[0]._MSAAFramebuffer) {
  12920. // Bind the correct framebuffer
  12921. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12922. }
  12923. onBeforeUnbind();
  12924. }
  12925. this.bindUnboundFramebuffer(null);
  12926. };
  12927. /**
  12928. * Force the mipmap generation for the given render target texture
  12929. * @param texture defines the render target texture to use
  12930. */
  12931. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12932. if (texture.generateMipMaps) {
  12933. var gl = this._gl;
  12934. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12935. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12936. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12937. }
  12938. };
  12939. /**
  12940. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12941. */
  12942. Engine.prototype.flushFramebuffer = function () {
  12943. this._gl.flush();
  12944. };
  12945. /**
  12946. * Unbind the current render target and bind the default framebuffer
  12947. */
  12948. Engine.prototype.restoreDefaultFramebuffer = function () {
  12949. if (this._currentRenderTarget) {
  12950. this.unBindFramebuffer(this._currentRenderTarget);
  12951. }
  12952. else {
  12953. this.bindUnboundFramebuffer(null);
  12954. }
  12955. if (this._cachedViewport) {
  12956. this.setViewport(this._cachedViewport);
  12957. }
  12958. this.wipeCaches();
  12959. };
  12960. // UBOs
  12961. /**
  12962. * Create an uniform buffer
  12963. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12964. * @param elements defines the content of the uniform buffer
  12965. * @returns the webGL uniform buffer
  12966. */
  12967. Engine.prototype.createUniformBuffer = function (elements) {
  12968. var ubo = this._gl.createBuffer();
  12969. if (!ubo) {
  12970. throw new Error("Unable to create uniform buffer");
  12971. }
  12972. this.bindUniformBuffer(ubo);
  12973. if (elements instanceof Float32Array) {
  12974. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12975. }
  12976. else {
  12977. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12978. }
  12979. this.bindUniformBuffer(null);
  12980. ubo.references = 1;
  12981. return ubo;
  12982. };
  12983. /**
  12984. * Create a dynamic uniform buffer
  12985. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12986. * @param elements defines the content of the uniform buffer
  12987. * @returns the webGL uniform buffer
  12988. */
  12989. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12990. var ubo = this._gl.createBuffer();
  12991. if (!ubo) {
  12992. throw new Error("Unable to create dynamic uniform buffer");
  12993. }
  12994. this.bindUniformBuffer(ubo);
  12995. if (elements instanceof Float32Array) {
  12996. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12997. }
  12998. else {
  12999. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13000. }
  13001. this.bindUniformBuffer(null);
  13002. ubo.references = 1;
  13003. return ubo;
  13004. };
  13005. /**
  13006. * Update an existing uniform buffer
  13007. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13008. * @param uniformBuffer defines the target uniform buffer
  13009. * @param elements defines the content to update
  13010. * @param offset defines the offset in the uniform buffer where update should start
  13011. * @param count defines the size of the data to update
  13012. */
  13013. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13014. this.bindUniformBuffer(uniformBuffer);
  13015. if (offset === undefined) {
  13016. offset = 0;
  13017. }
  13018. if (count === undefined) {
  13019. if (elements instanceof Float32Array) {
  13020. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13021. }
  13022. else {
  13023. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13024. }
  13025. }
  13026. else {
  13027. if (elements instanceof Float32Array) {
  13028. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13029. }
  13030. else {
  13031. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13032. }
  13033. }
  13034. this.bindUniformBuffer(null);
  13035. };
  13036. // VBOs
  13037. Engine.prototype._resetVertexBufferBinding = function () {
  13038. this.bindArrayBuffer(null);
  13039. this._cachedVertexBuffers = null;
  13040. };
  13041. /**
  13042. * Creates a vertex buffer
  13043. * @param data the data for the vertex buffer
  13044. * @returns the new WebGL static buffer
  13045. */
  13046. Engine.prototype.createVertexBuffer = function (data) {
  13047. var vbo = this._gl.createBuffer();
  13048. if (!vbo) {
  13049. throw new Error("Unable to create vertex buffer");
  13050. }
  13051. this.bindArrayBuffer(vbo);
  13052. if (data instanceof Array) {
  13053. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13054. }
  13055. else {
  13056. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13057. }
  13058. this._resetVertexBufferBinding();
  13059. vbo.references = 1;
  13060. return vbo;
  13061. };
  13062. /**
  13063. * Creates a dynamic vertex buffer
  13064. * @param data the data for the dynamic vertex buffer
  13065. * @returns the new WebGL dynamic buffer
  13066. */
  13067. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13068. var vbo = this._gl.createBuffer();
  13069. if (!vbo) {
  13070. throw new Error("Unable to create dynamic vertex buffer");
  13071. }
  13072. this.bindArrayBuffer(vbo);
  13073. if (data instanceof Array) {
  13074. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13075. }
  13076. else {
  13077. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13078. }
  13079. this._resetVertexBufferBinding();
  13080. vbo.references = 1;
  13081. return vbo;
  13082. };
  13083. /**
  13084. * Update a dynamic index buffer
  13085. * @param indexBuffer defines the target index buffer
  13086. * @param indices defines the data to update
  13087. * @param offset defines the offset in the target index buffer where update should start
  13088. */
  13089. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13090. if (offset === void 0) { offset = 0; }
  13091. // Force cache update
  13092. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13093. this.bindIndexBuffer(indexBuffer);
  13094. var arrayBuffer;
  13095. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13096. arrayBuffer = indices;
  13097. }
  13098. else {
  13099. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13100. }
  13101. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13102. this._resetIndexBufferBinding();
  13103. };
  13104. /**
  13105. * Updates a dynamic vertex buffer.
  13106. * @param vertexBuffer the vertex buffer to update
  13107. * @param data the data used to update the vertex buffer
  13108. * @param byteOffset the byte offset of the data
  13109. * @param byteLength the byte length of the data
  13110. */
  13111. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13112. this.bindArrayBuffer(vertexBuffer);
  13113. if (byteOffset === undefined) {
  13114. byteOffset = 0;
  13115. }
  13116. if (byteLength === undefined) {
  13117. if (data instanceof Array) {
  13118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13119. }
  13120. else {
  13121. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13122. }
  13123. }
  13124. else {
  13125. if (data instanceof Array) {
  13126. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13127. }
  13128. else {
  13129. if (data instanceof ArrayBuffer) {
  13130. data = new Uint8Array(data, byteOffset, byteLength);
  13131. }
  13132. else {
  13133. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13134. }
  13135. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13136. }
  13137. }
  13138. this._resetVertexBufferBinding();
  13139. };
  13140. Engine.prototype._resetIndexBufferBinding = function () {
  13141. this.bindIndexBuffer(null);
  13142. this._cachedIndexBuffer = null;
  13143. };
  13144. /**
  13145. * Creates a new index buffer
  13146. * @param indices defines the content of the index buffer
  13147. * @param updatable defines if the index buffer must be updatable
  13148. * @returns a new webGL buffer
  13149. */
  13150. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13151. var vbo = this._gl.createBuffer();
  13152. if (!vbo) {
  13153. throw new Error("Unable to create index buffer");
  13154. }
  13155. this.bindIndexBuffer(vbo);
  13156. // Check for 32 bits indices
  13157. var arrayBuffer;
  13158. var need32Bits = false;
  13159. if (indices instanceof Uint16Array) {
  13160. arrayBuffer = indices;
  13161. }
  13162. else {
  13163. //check 32 bit support
  13164. if (this._caps.uintIndices) {
  13165. if (indices instanceof Uint32Array) {
  13166. arrayBuffer = indices;
  13167. need32Bits = true;
  13168. }
  13169. else {
  13170. //number[] or Int32Array, check if 32 bit is necessary
  13171. for (var index = 0; index < indices.length; index++) {
  13172. if (indices[index] > 65535) {
  13173. need32Bits = true;
  13174. break;
  13175. }
  13176. }
  13177. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13178. }
  13179. }
  13180. else {
  13181. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13182. arrayBuffer = new Uint16Array(indices);
  13183. }
  13184. }
  13185. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13186. this._resetIndexBufferBinding();
  13187. vbo.references = 1;
  13188. vbo.is32Bits = need32Bits;
  13189. return vbo;
  13190. };
  13191. /**
  13192. * Bind a webGL buffer to the webGL context
  13193. * @param buffer defines the buffer to bind
  13194. */
  13195. Engine.prototype.bindArrayBuffer = function (buffer) {
  13196. if (!this._vaoRecordInProgress) {
  13197. this._unbindVertexArrayObject();
  13198. }
  13199. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13200. };
  13201. /**
  13202. * Bind an uniform buffer to the current webGL context
  13203. * @param buffer defines the buffer to bind
  13204. */
  13205. Engine.prototype.bindUniformBuffer = function (buffer) {
  13206. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13207. };
  13208. /**
  13209. * Bind a buffer to the current webGL context at a given location
  13210. * @param buffer defines the buffer to bind
  13211. * @param location defines the index where to bind the buffer
  13212. */
  13213. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13214. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13215. };
  13216. /**
  13217. * Bind a specific block at a given index in a specific shader program
  13218. * @param shaderProgram defines the shader program
  13219. * @param blockName defines the block name
  13220. * @param index defines the index where to bind the block
  13221. */
  13222. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13223. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13224. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13225. };
  13226. ;
  13227. Engine.prototype.bindIndexBuffer = function (buffer) {
  13228. if (!this._vaoRecordInProgress) {
  13229. this._unbindVertexArrayObject();
  13230. }
  13231. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13232. };
  13233. Engine.prototype.bindBuffer = function (buffer, target) {
  13234. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13235. this._gl.bindBuffer(target, buffer);
  13236. this._currentBoundBuffer[target] = buffer;
  13237. }
  13238. };
  13239. /**
  13240. * update the bound buffer with the given data
  13241. * @param data defines the data to update
  13242. */
  13243. Engine.prototype.updateArrayBuffer = function (data) {
  13244. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13245. };
  13246. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13247. var pointer = this._currentBufferPointers[indx];
  13248. var changed = false;
  13249. if (!pointer.active) {
  13250. changed = true;
  13251. pointer.active = true;
  13252. pointer.index = indx;
  13253. pointer.size = size;
  13254. pointer.type = type;
  13255. pointer.normalized = normalized;
  13256. pointer.stride = stride;
  13257. pointer.offset = offset;
  13258. pointer.buffer = buffer;
  13259. }
  13260. else {
  13261. if (pointer.buffer !== buffer) {
  13262. pointer.buffer = buffer;
  13263. changed = true;
  13264. }
  13265. if (pointer.size !== size) {
  13266. pointer.size = size;
  13267. changed = true;
  13268. }
  13269. if (pointer.type !== type) {
  13270. pointer.type = type;
  13271. changed = true;
  13272. }
  13273. if (pointer.normalized !== normalized) {
  13274. pointer.normalized = normalized;
  13275. changed = true;
  13276. }
  13277. if (pointer.stride !== stride) {
  13278. pointer.stride = stride;
  13279. changed = true;
  13280. }
  13281. if (pointer.offset !== offset) {
  13282. pointer.offset = offset;
  13283. changed = true;
  13284. }
  13285. }
  13286. if (changed || this._vaoRecordInProgress) {
  13287. this.bindArrayBuffer(buffer);
  13288. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13289. }
  13290. };
  13291. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13292. if (indexBuffer == null) {
  13293. return;
  13294. }
  13295. if (this._cachedIndexBuffer !== indexBuffer) {
  13296. this._cachedIndexBuffer = indexBuffer;
  13297. this.bindIndexBuffer(indexBuffer);
  13298. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13299. }
  13300. };
  13301. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13302. var attributes = effect.getAttributesNames();
  13303. if (!this._vaoRecordInProgress) {
  13304. this._unbindVertexArrayObject();
  13305. }
  13306. this.unbindAllAttributes();
  13307. for (var index = 0; index < attributes.length; index++) {
  13308. var order = effect.getAttributeLocation(index);
  13309. if (order >= 0) {
  13310. var vertexBuffer = vertexBuffers[attributes[index]];
  13311. if (!vertexBuffer) {
  13312. continue;
  13313. }
  13314. this._gl.enableVertexAttribArray(order);
  13315. if (!this._vaoRecordInProgress) {
  13316. this._vertexAttribArraysEnabled[order] = true;
  13317. }
  13318. var buffer = vertexBuffer.getBuffer();
  13319. if (buffer) {
  13320. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13321. if (vertexBuffer.getIsInstanced()) {
  13322. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13323. if (!this._vaoRecordInProgress) {
  13324. this._currentInstanceLocations.push(order);
  13325. this._currentInstanceBuffers.push(buffer);
  13326. }
  13327. }
  13328. }
  13329. }
  13330. }
  13331. };
  13332. /**
  13333. * Records a vertex array object
  13334. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13335. * @param vertexBuffers defines the list of vertex buffers to store
  13336. * @param indexBuffer defines the index buffer to store
  13337. * @param effect defines the effect to store
  13338. * @returns the new vertex array object
  13339. */
  13340. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13341. var vao = this._gl.createVertexArray();
  13342. this._vaoRecordInProgress = true;
  13343. this._gl.bindVertexArray(vao);
  13344. this._mustWipeVertexAttributes = true;
  13345. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13346. this.bindIndexBuffer(indexBuffer);
  13347. this._vaoRecordInProgress = false;
  13348. this._gl.bindVertexArray(null);
  13349. return vao;
  13350. };
  13351. /**
  13352. * Bind a specific vertex array object
  13353. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13354. * @param vertexArrayObject defines the vertex array object to bind
  13355. * @param indexBuffer defines the index buffer to bind
  13356. */
  13357. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13358. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13359. this._cachedVertexArrayObject = vertexArrayObject;
  13360. this._gl.bindVertexArray(vertexArrayObject);
  13361. this._cachedVertexBuffers = null;
  13362. this._cachedIndexBuffer = null;
  13363. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13364. this._mustWipeVertexAttributes = true;
  13365. }
  13366. };
  13367. /**
  13368. * Bind webGl buffers directly to the webGL context
  13369. * @param vertexBuffer defines the vertex buffer to bind
  13370. * @param indexBuffer defines the index buffer to bind
  13371. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13372. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13373. * @param effect defines the effect associated with the vertex buffer
  13374. */
  13375. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13376. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13377. this._cachedVertexBuffers = vertexBuffer;
  13378. this._cachedEffectForVertexBuffers = effect;
  13379. var attributesCount = effect.getAttributesCount();
  13380. this._unbindVertexArrayObject();
  13381. this.unbindAllAttributes();
  13382. var offset = 0;
  13383. for (var index = 0; index < attributesCount; index++) {
  13384. if (index < vertexDeclaration.length) {
  13385. var order = effect.getAttributeLocation(index);
  13386. if (order >= 0) {
  13387. this._gl.enableVertexAttribArray(order);
  13388. this._vertexAttribArraysEnabled[order] = true;
  13389. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13390. }
  13391. offset += vertexDeclaration[index] * 4;
  13392. }
  13393. }
  13394. }
  13395. this._bindIndexBufferWithCache(indexBuffer);
  13396. };
  13397. Engine.prototype._unbindVertexArrayObject = function () {
  13398. if (!this._cachedVertexArrayObject) {
  13399. return;
  13400. }
  13401. this._cachedVertexArrayObject = null;
  13402. this._gl.bindVertexArray(null);
  13403. };
  13404. /**
  13405. * Bind a list of vertex buffers to the webGL context
  13406. * @param vertexBuffers defines the list of vertex buffers to bind
  13407. * @param indexBuffer defines the index buffer to bind
  13408. * @param effect defines the effect associated with the vertex buffers
  13409. */
  13410. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13411. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13412. this._cachedVertexBuffers = vertexBuffers;
  13413. this._cachedEffectForVertexBuffers = effect;
  13414. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13415. }
  13416. this._bindIndexBufferWithCache(indexBuffer);
  13417. };
  13418. /**
  13419. * Unbind all instance attributes
  13420. */
  13421. Engine.prototype.unbindInstanceAttributes = function () {
  13422. var boundBuffer;
  13423. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13424. var instancesBuffer = this._currentInstanceBuffers[i];
  13425. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13426. boundBuffer = instancesBuffer;
  13427. this.bindArrayBuffer(instancesBuffer);
  13428. }
  13429. var offsetLocation = this._currentInstanceLocations[i];
  13430. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13431. }
  13432. this._currentInstanceBuffers.length = 0;
  13433. this._currentInstanceLocations.length = 0;
  13434. };
  13435. /**
  13436. * Release and free the memory of a vertex array object
  13437. * @param vao defines the vertex array object to delete
  13438. */
  13439. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13440. this._gl.deleteVertexArray(vao);
  13441. };
  13442. /** @hidden */
  13443. Engine.prototype._releaseBuffer = function (buffer) {
  13444. buffer.references--;
  13445. if (buffer.references === 0) {
  13446. this._gl.deleteBuffer(buffer);
  13447. return true;
  13448. }
  13449. return false;
  13450. };
  13451. /**
  13452. * Creates a webGL buffer to use with instanciation
  13453. * @param capacity defines the size of the buffer
  13454. * @returns the webGL buffer
  13455. */
  13456. Engine.prototype.createInstancesBuffer = function (capacity) {
  13457. var buffer = this._gl.createBuffer();
  13458. if (!buffer) {
  13459. throw new Error("Unable to create instance buffer");
  13460. }
  13461. buffer.capacity = capacity;
  13462. this.bindArrayBuffer(buffer);
  13463. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13464. return buffer;
  13465. };
  13466. /**
  13467. * Delete a webGL buffer used with instanciation
  13468. * @param buffer defines the webGL buffer to delete
  13469. */
  13470. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13471. this._gl.deleteBuffer(buffer);
  13472. };
  13473. /**
  13474. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13475. * @param instancesBuffer defines the webGL buffer to update and bind
  13476. * @param data defines the data to store in the buffer
  13477. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13478. */
  13479. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13480. this.bindArrayBuffer(instancesBuffer);
  13481. if (data) {
  13482. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13483. }
  13484. if (offsetLocations[0].index !== undefined) {
  13485. var stride = 0;
  13486. for (var i = 0; i < offsetLocations.length; i++) {
  13487. var ai = offsetLocations[i];
  13488. stride += ai.attributeSize * 4;
  13489. }
  13490. for (var i = 0; i < offsetLocations.length; i++) {
  13491. var ai = offsetLocations[i];
  13492. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13493. this._gl.enableVertexAttribArray(ai.index);
  13494. this._vertexAttribArraysEnabled[ai.index] = true;
  13495. }
  13496. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13497. this._gl.vertexAttribDivisor(ai.index, 1);
  13498. this._currentInstanceLocations.push(ai.index);
  13499. this._currentInstanceBuffers.push(instancesBuffer);
  13500. }
  13501. }
  13502. else {
  13503. for (var index = 0; index < 4; index++) {
  13504. var offsetLocation = offsetLocations[index];
  13505. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13506. this._gl.enableVertexAttribArray(offsetLocation);
  13507. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13508. }
  13509. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13510. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13511. this._currentInstanceLocations.push(offsetLocation);
  13512. this._currentInstanceBuffers.push(instancesBuffer);
  13513. }
  13514. }
  13515. };
  13516. /**
  13517. * Apply all cached states (depth, culling, stencil and alpha)
  13518. */
  13519. Engine.prototype.applyStates = function () {
  13520. this._depthCullingState.apply(this._gl);
  13521. this._stencilState.apply(this._gl);
  13522. this._alphaState.apply(this._gl);
  13523. };
  13524. /**
  13525. * Send a draw order
  13526. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13527. * @param indexStart defines the starting index
  13528. * @param indexCount defines the number of index to draw
  13529. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13530. */
  13531. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13532. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13533. };
  13534. /**
  13535. * Draw a list of points
  13536. * @param verticesStart defines the index of first vertex to draw
  13537. * @param verticesCount defines the count of vertices to draw
  13538. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13539. */
  13540. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13541. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13542. };
  13543. /**
  13544. * Draw a list of unindexed primitives
  13545. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13546. * @param verticesStart defines the index of first vertex to draw
  13547. * @param verticesCount defines the count of vertices to draw
  13548. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13549. */
  13550. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13551. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13552. };
  13553. /**
  13554. * Draw a list of indexed primitives
  13555. * @param fillMode defines the primitive to use
  13556. * @param indexStart defines the starting index
  13557. * @param indexCount defines the number of index to draw
  13558. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13559. */
  13560. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13561. // Apply states
  13562. this.applyStates();
  13563. this._drawCalls.addCount(1, false);
  13564. // Render
  13565. var drawMode = this._drawMode(fillMode);
  13566. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13567. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13568. if (instancesCount) {
  13569. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13570. }
  13571. else {
  13572. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13573. }
  13574. };
  13575. /**
  13576. * Draw a list of unindexed primitives
  13577. * @param fillMode defines the primitive to use
  13578. * @param verticesStart defines the index of first vertex to draw
  13579. * @param verticesCount defines the count of vertices to draw
  13580. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13581. */
  13582. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13583. // Apply states
  13584. this.applyStates();
  13585. this._drawCalls.addCount(1, false);
  13586. var drawMode = this._drawMode(fillMode);
  13587. if (instancesCount) {
  13588. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13589. }
  13590. else {
  13591. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13592. }
  13593. };
  13594. Engine.prototype._drawMode = function (fillMode) {
  13595. switch (fillMode) {
  13596. // Triangle views
  13597. case BABYLON.Material.TriangleFillMode:
  13598. return this._gl.TRIANGLES;
  13599. case BABYLON.Material.PointFillMode:
  13600. return this._gl.POINTS;
  13601. case BABYLON.Material.WireFrameFillMode:
  13602. return this._gl.LINES;
  13603. // Draw modes
  13604. case BABYLON.Material.PointListDrawMode:
  13605. return this._gl.POINTS;
  13606. case BABYLON.Material.LineListDrawMode:
  13607. return this._gl.LINES;
  13608. case BABYLON.Material.LineLoopDrawMode:
  13609. return this._gl.LINE_LOOP;
  13610. case BABYLON.Material.LineStripDrawMode:
  13611. return this._gl.LINE_STRIP;
  13612. case BABYLON.Material.TriangleStripDrawMode:
  13613. return this._gl.TRIANGLE_STRIP;
  13614. case BABYLON.Material.TriangleFanDrawMode:
  13615. return this._gl.TRIANGLE_FAN;
  13616. default:
  13617. return this._gl.TRIANGLES;
  13618. }
  13619. };
  13620. // Shaders
  13621. /** @hidden */
  13622. Engine.prototype._releaseEffect = function (effect) {
  13623. if (this._compiledEffects[effect._key]) {
  13624. delete this._compiledEffects[effect._key];
  13625. this._deleteProgram(effect.getProgram());
  13626. }
  13627. };
  13628. /** @hidden */
  13629. Engine.prototype._deleteProgram = function (program) {
  13630. if (program) {
  13631. program.__SPECTOR_rebuildProgram = null;
  13632. if (program.transformFeedback) {
  13633. this.deleteTransformFeedback(program.transformFeedback);
  13634. program.transformFeedback = null;
  13635. }
  13636. this._gl.deleteProgram(program);
  13637. }
  13638. };
  13639. /**
  13640. * Create a new effect (used to store vertex/fragment shaders)
  13641. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13642. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13643. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13644. * @param samplers defines an array of string used to represent textures
  13645. * @param defines defines the string containing the defines to use to compile the shaders
  13646. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13647. * @param onCompiled defines a function to call when the effect creation is successful
  13648. * @param onError defines a function to call when the effect creation has failed
  13649. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13650. * @returns the new Effect
  13651. */
  13652. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13653. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13654. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13655. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13656. if (this._compiledEffects[name]) {
  13657. var compiledEffect = this._compiledEffects[name];
  13658. if (onCompiled && compiledEffect.isReady()) {
  13659. onCompiled(compiledEffect);
  13660. }
  13661. return compiledEffect;
  13662. }
  13663. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13664. effect._key = name;
  13665. this._compiledEffects[name] = effect;
  13666. return effect;
  13667. };
  13668. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13669. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13670. };
  13671. ;
  13672. Engine.prototype._compileRawShader = function (source, type) {
  13673. var gl = this._gl;
  13674. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13675. gl.shaderSource(shader, source);
  13676. gl.compileShader(shader);
  13677. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13678. var log = gl.getShaderInfoLog(shader);
  13679. if (log) {
  13680. throw new Error(log);
  13681. }
  13682. }
  13683. if (!shader) {
  13684. throw new Error("Something went wrong while compile the shader.");
  13685. }
  13686. return shader;
  13687. };
  13688. ;
  13689. /**
  13690. * Directly creates a webGL program
  13691. * @param vertexCode defines the vertex shader code to use
  13692. * @param fragmentCode defines the fragment shader code to use
  13693. * @param context defines the webGL context to use (if not set, the current one will be used)
  13694. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13695. * @returns the new webGL program
  13696. */
  13697. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13698. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13699. context = context || this._gl;
  13700. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13701. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13702. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13703. };
  13704. /**
  13705. * Creates a webGL program
  13706. * @param vertexCode defines the vertex shader code to use
  13707. * @param fragmentCode defines the fragment shader code to use
  13708. * @param defines defines the string containing the defines to use to compile the shaders
  13709. * @param context defines the webGL context to use (if not set, the current one will be used)
  13710. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13711. * @returns the new webGL program
  13712. */
  13713. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13714. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13715. context = context || this._gl;
  13716. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13717. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13718. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13719. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13720. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13721. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13722. return program;
  13723. };
  13724. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13725. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13726. var shaderProgram = context.createProgram();
  13727. if (!shaderProgram) {
  13728. throw new Error("Unable to create program");
  13729. }
  13730. context.attachShader(shaderProgram, vertexShader);
  13731. context.attachShader(shaderProgram, fragmentShader);
  13732. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13733. var transformFeedback = this.createTransformFeedback();
  13734. this.bindTransformFeedback(transformFeedback);
  13735. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13736. shaderProgram.transformFeedback = transformFeedback;
  13737. }
  13738. context.linkProgram(shaderProgram);
  13739. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13740. this.bindTransformFeedback(null);
  13741. }
  13742. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13743. if (!linked) {
  13744. var error = context.getProgramInfoLog(shaderProgram);
  13745. if (error) {
  13746. throw new Error(error);
  13747. }
  13748. }
  13749. if (this.validateShaderPrograms) {
  13750. context.validateProgram(shaderProgram);
  13751. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13752. if (!validated) {
  13753. var error = context.getProgramInfoLog(shaderProgram);
  13754. if (error) {
  13755. throw new Error(error);
  13756. }
  13757. }
  13758. }
  13759. context.deleteShader(vertexShader);
  13760. context.deleteShader(fragmentShader);
  13761. return shaderProgram;
  13762. };
  13763. /**
  13764. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13765. * @param shaderProgram defines the webGL program to use
  13766. * @param uniformsNames defines the list of uniform names
  13767. * @returns an array of webGL uniform locations
  13768. */
  13769. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13770. var results = new Array();
  13771. for (var index = 0; index < uniformsNames.length; index++) {
  13772. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13773. }
  13774. return results;
  13775. };
  13776. /**
  13777. * Gets the lsit of active attributes for a given webGL program
  13778. * @param shaderProgram defines the webGL program to use
  13779. * @param attributesNames defines the list of attribute names to get
  13780. * @returns an array of indices indicating the offset of each attribute
  13781. */
  13782. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13783. var results = [];
  13784. for (var index = 0; index < attributesNames.length; index++) {
  13785. try {
  13786. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13787. }
  13788. catch (e) {
  13789. results.push(-1);
  13790. }
  13791. }
  13792. return results;
  13793. };
  13794. /**
  13795. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13796. * @param effect defines the effect to activate
  13797. */
  13798. Engine.prototype.enableEffect = function (effect) {
  13799. if (!effect || effect === this._currentEffect) {
  13800. return;
  13801. }
  13802. // Use program
  13803. this.bindSamplers(effect);
  13804. this._currentEffect = effect;
  13805. if (effect.onBind) {
  13806. effect.onBind(effect);
  13807. }
  13808. if (effect._onBindObservable) {
  13809. effect._onBindObservable.notifyObservers(effect);
  13810. }
  13811. };
  13812. /**
  13813. * Set the value of an uniform to an array of int32
  13814. * @param uniform defines the webGL uniform location where to store the value
  13815. * @param array defines the array of int32 to store
  13816. */
  13817. Engine.prototype.setIntArray = function (uniform, array) {
  13818. if (!uniform)
  13819. return;
  13820. this._gl.uniform1iv(uniform, array);
  13821. };
  13822. /**
  13823. * Set the value of an uniform to an array of int32 (stored as vec2)
  13824. * @param uniform defines the webGL uniform location where to store the value
  13825. * @param array defines the array of int32 to store
  13826. */
  13827. Engine.prototype.setIntArray2 = function (uniform, array) {
  13828. if (!uniform || array.length % 2 !== 0)
  13829. return;
  13830. this._gl.uniform2iv(uniform, array);
  13831. };
  13832. /**
  13833. * Set the value of an uniform to an array of int32 (stored as vec3)
  13834. * @param uniform defines the webGL uniform location where to store the value
  13835. * @param array defines the array of int32 to store
  13836. */
  13837. Engine.prototype.setIntArray3 = function (uniform, array) {
  13838. if (!uniform || array.length % 3 !== 0)
  13839. return;
  13840. this._gl.uniform3iv(uniform, array);
  13841. };
  13842. /**
  13843. * Set the value of an uniform to an array of int32 (stored as vec4)
  13844. * @param uniform defines the webGL uniform location where to store the value
  13845. * @param array defines the array of int32 to store
  13846. */
  13847. Engine.prototype.setIntArray4 = function (uniform, array) {
  13848. if (!uniform || array.length % 4 !== 0)
  13849. return;
  13850. this._gl.uniform4iv(uniform, array);
  13851. };
  13852. /**
  13853. * Set the value of an uniform to an array of float32
  13854. * @param uniform defines the webGL uniform location where to store the value
  13855. * @param array defines the array of float32 to store
  13856. */
  13857. Engine.prototype.setFloatArray = function (uniform, array) {
  13858. if (!uniform)
  13859. return;
  13860. this._gl.uniform1fv(uniform, array);
  13861. };
  13862. /**
  13863. * Set the value of an uniform to an array of float32 (stored as vec2)
  13864. * @param uniform defines the webGL uniform location where to store the value
  13865. * @param array defines the array of float32 to store
  13866. */
  13867. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13868. if (!uniform || array.length % 2 !== 0)
  13869. return;
  13870. this._gl.uniform2fv(uniform, array);
  13871. };
  13872. /**
  13873. * Set the value of an uniform to an array of float32 (stored as vec3)
  13874. * @param uniform defines the webGL uniform location where to store the value
  13875. * @param array defines the array of float32 to store
  13876. */
  13877. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13878. if (!uniform || array.length % 3 !== 0)
  13879. return;
  13880. this._gl.uniform3fv(uniform, array);
  13881. };
  13882. /**
  13883. * Set the value of an uniform to an array of float32 (stored as vec4)
  13884. * @param uniform defines the webGL uniform location where to store the value
  13885. * @param array defines the array of float32 to store
  13886. */
  13887. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13888. if (!uniform || array.length % 4 !== 0)
  13889. return;
  13890. this._gl.uniform4fv(uniform, array);
  13891. };
  13892. /**
  13893. * Set the value of an uniform to an array of number
  13894. * @param uniform defines the webGL uniform location where to store the value
  13895. * @param array defines the array of number to store
  13896. */
  13897. Engine.prototype.setArray = function (uniform, array) {
  13898. if (!uniform)
  13899. return;
  13900. this._gl.uniform1fv(uniform, array);
  13901. };
  13902. /**
  13903. * Set the value of an uniform to an array of number (stored as vec2)
  13904. * @param uniform defines the webGL uniform location where to store the value
  13905. * @param array defines the array of number to store
  13906. */
  13907. Engine.prototype.setArray2 = function (uniform, array) {
  13908. if (!uniform || array.length % 2 !== 0)
  13909. return;
  13910. this._gl.uniform2fv(uniform, array);
  13911. };
  13912. /**
  13913. * Set the value of an uniform to an array of number (stored as vec3)
  13914. * @param uniform defines the webGL uniform location where to store the value
  13915. * @param array defines the array of number to store
  13916. */
  13917. Engine.prototype.setArray3 = function (uniform, array) {
  13918. if (!uniform || array.length % 3 !== 0)
  13919. return;
  13920. this._gl.uniform3fv(uniform, array);
  13921. };
  13922. /**
  13923. * Set the value of an uniform to an array of number (stored as vec4)
  13924. * @param uniform defines the webGL uniform location where to store the value
  13925. * @param array defines the array of number to store
  13926. */
  13927. Engine.prototype.setArray4 = function (uniform, array) {
  13928. if (!uniform || array.length % 4 !== 0)
  13929. return;
  13930. this._gl.uniform4fv(uniform, array);
  13931. };
  13932. /**
  13933. * Set the value of an uniform to an array of float32 (stored as matrices)
  13934. * @param uniform defines the webGL uniform location where to store the value
  13935. * @param matrices defines the array of float32 to store
  13936. */
  13937. Engine.prototype.setMatrices = function (uniform, matrices) {
  13938. if (!uniform)
  13939. return;
  13940. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13941. };
  13942. /**
  13943. * Set the value of an uniform to a matrix
  13944. * @param uniform defines the webGL uniform location where to store the value
  13945. * @param matrix defines the matrix to store
  13946. */
  13947. Engine.prototype.setMatrix = function (uniform, matrix) {
  13948. if (!uniform)
  13949. return;
  13950. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13951. };
  13952. /**
  13953. * Set the value of an uniform to a matrix (3x3)
  13954. * @param uniform defines the webGL uniform location where to store the value
  13955. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13956. */
  13957. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13958. if (!uniform)
  13959. return;
  13960. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13961. };
  13962. /**
  13963. * Set the value of an uniform to a matrix (2x2)
  13964. * @param uniform defines the webGL uniform location where to store the value
  13965. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13966. */
  13967. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13968. if (!uniform)
  13969. return;
  13970. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13971. };
  13972. /**
  13973. * Set the value of an uniform to a number (int)
  13974. * @param uniform defines the webGL uniform location where to store the value
  13975. * @param value defines the int number to store
  13976. */
  13977. Engine.prototype.setInt = function (uniform, value) {
  13978. if (!uniform)
  13979. return;
  13980. this._gl.uniform1i(uniform, value);
  13981. };
  13982. /**
  13983. * Set the value of an uniform to a number (float)
  13984. * @param uniform defines the webGL uniform location where to store the value
  13985. * @param value defines the float number to store
  13986. */
  13987. Engine.prototype.setFloat = function (uniform, value) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform1f(uniform, value);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a vec2
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param x defines the 1st component of the value
  13996. * @param y defines the 2nd component of the value
  13997. */
  13998. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13999. if (!uniform)
  14000. return;
  14001. this._gl.uniform2f(uniform, x, y);
  14002. };
  14003. /**
  14004. * Set the value of an uniform to a vec3
  14005. * @param uniform defines the webGL uniform location where to store the value
  14006. * @param x defines the 1st component of the value
  14007. * @param y defines the 2nd component of the value
  14008. * @param z defines the 3rd component of the value
  14009. */
  14010. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14011. if (!uniform)
  14012. return;
  14013. this._gl.uniform3f(uniform, x, y, z);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to a boolean
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param bool defines the boolean to store
  14019. */
  14020. Engine.prototype.setBool = function (uniform, bool) {
  14021. if (!uniform)
  14022. return;
  14023. this._gl.uniform1i(uniform, bool);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to a vec4
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param x defines the 1st component of the value
  14029. * @param y defines the 2nd component of the value
  14030. * @param z defines the 3rd component of the value
  14031. * @param w defines the 4th component of the value
  14032. */
  14033. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14034. if (!uniform)
  14035. return;
  14036. this._gl.uniform4f(uniform, x, y, z, w);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to a Color3
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param color3 defines the color to store
  14042. */
  14043. Engine.prototype.setColor3 = function (uniform, color3) {
  14044. if (!uniform)
  14045. return;
  14046. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to a Color3 and an alpha value
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param color3 defines the color to store
  14052. * @param alpha defines the alpha component to store
  14053. */
  14054. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14055. if (!uniform)
  14056. return;
  14057. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14058. };
  14059. /**
  14060. * Sets a Color4 on a uniform variable
  14061. * @param uniform defines the uniform location
  14062. * @param color4 defines the value to be set
  14063. */
  14064. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14065. if (!uniform)
  14066. return;
  14067. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14068. };
  14069. // States
  14070. /**
  14071. * Set various states to the webGL context
  14072. * @param culling defines backface culling state
  14073. * @param zOffset defines the value to apply to zOffset (0 by default)
  14074. * @param force defines if states must be applied even if cache is up to date
  14075. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14076. */
  14077. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14078. if (zOffset === void 0) { zOffset = 0; }
  14079. if (reverseSide === void 0) { reverseSide = false; }
  14080. // Culling
  14081. if (this._depthCullingState.cull !== culling || force) {
  14082. this._depthCullingState.cull = culling;
  14083. }
  14084. // Cull face
  14085. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14086. if (this._depthCullingState.cullFace !== cullFace || force) {
  14087. this._depthCullingState.cullFace = cullFace;
  14088. }
  14089. // Z offset
  14090. this.setZOffset(zOffset);
  14091. // Front face
  14092. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14093. if (this._depthCullingState.frontFace !== frontFace || force) {
  14094. this._depthCullingState.frontFace = frontFace;
  14095. }
  14096. };
  14097. /**
  14098. * Set the z offset to apply to current rendering
  14099. * @param value defines the offset to apply
  14100. */
  14101. Engine.prototype.setZOffset = function (value) {
  14102. this._depthCullingState.zOffset = value;
  14103. };
  14104. /**
  14105. * Gets the current value of the zOffset
  14106. * @returns the current zOffset state
  14107. */
  14108. Engine.prototype.getZOffset = function () {
  14109. return this._depthCullingState.zOffset;
  14110. };
  14111. /**
  14112. * Enable or disable depth buffering
  14113. * @param enable defines the state to set
  14114. */
  14115. Engine.prototype.setDepthBuffer = function (enable) {
  14116. this._depthCullingState.depthTest = enable;
  14117. };
  14118. /**
  14119. * Gets a boolean indicating if depth writing is enabled
  14120. * @returns the current depth writing state
  14121. */
  14122. Engine.prototype.getDepthWrite = function () {
  14123. return this._depthCullingState.depthMask;
  14124. };
  14125. /**
  14126. * Enable or disable depth writing
  14127. * @param enable defines the state to set
  14128. */
  14129. Engine.prototype.setDepthWrite = function (enable) {
  14130. this._depthCullingState.depthMask = enable;
  14131. };
  14132. /**
  14133. * Enable or disable color writing
  14134. * @param enable defines the state to set
  14135. */
  14136. Engine.prototype.setColorWrite = function (enable) {
  14137. this._gl.colorMask(enable, enable, enable, enable);
  14138. this._colorWrite = enable;
  14139. };
  14140. /**
  14141. * Gets a boolean indicating if color writing is enabled
  14142. * @returns the current color writing state
  14143. */
  14144. Engine.prototype.getColorWrite = function () {
  14145. return this._colorWrite;
  14146. };
  14147. /**
  14148. * Sets alpha constants used by some alpha blending modes
  14149. * @param r defines the red component
  14150. * @param g defines the green component
  14151. * @param b defines the blue component
  14152. * @param a defines the alpha component
  14153. */
  14154. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14155. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14156. };
  14157. /**
  14158. * Sets the current alpha mode
  14159. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14160. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14161. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14162. */
  14163. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14164. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14165. if (this._alphaMode === mode) {
  14166. return;
  14167. }
  14168. switch (mode) {
  14169. case Engine.ALPHA_DISABLE:
  14170. this._alphaState.alphaBlend = false;
  14171. break;
  14172. case Engine.ALPHA_PREMULTIPLIED:
  14173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14174. this._alphaState.alphaBlend = true;
  14175. break;
  14176. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14177. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14178. this._alphaState.alphaBlend = true;
  14179. break;
  14180. case Engine.ALPHA_COMBINE:
  14181. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14182. this._alphaState.alphaBlend = true;
  14183. break;
  14184. case Engine.ALPHA_ONEONE:
  14185. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14186. this._alphaState.alphaBlend = true;
  14187. break;
  14188. case Engine.ALPHA_ADD:
  14189. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14190. this._alphaState.alphaBlend = true;
  14191. break;
  14192. case Engine.ALPHA_SUBTRACT:
  14193. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14194. this._alphaState.alphaBlend = true;
  14195. break;
  14196. case Engine.ALPHA_MULTIPLY:
  14197. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14198. this._alphaState.alphaBlend = true;
  14199. break;
  14200. case Engine.ALPHA_MAXIMIZED:
  14201. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14202. this._alphaState.alphaBlend = true;
  14203. break;
  14204. case Engine.ALPHA_INTERPOLATE:
  14205. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14206. this._alphaState.alphaBlend = true;
  14207. break;
  14208. case Engine.ALPHA_SCREENMODE:
  14209. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14210. this._alphaState.alphaBlend = true;
  14211. break;
  14212. }
  14213. if (!noDepthWriteChange) {
  14214. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14215. }
  14216. this._alphaMode = mode;
  14217. };
  14218. /**
  14219. * Gets the current alpha mode
  14220. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14221. * @returns the current alpha mode
  14222. */
  14223. Engine.prototype.getAlphaMode = function () {
  14224. return this._alphaMode;
  14225. };
  14226. // Textures
  14227. /**
  14228. * Clears the list of texture accessible through engine.
  14229. * This can help preventing texture load conflict due to name collision.
  14230. */
  14231. Engine.prototype.clearInternalTexturesCache = function () {
  14232. this._internalTexturesCache = [];
  14233. };
  14234. /**
  14235. * Force the entire cache to be cleared
  14236. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14237. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14238. */
  14239. Engine.prototype.wipeCaches = function (bruteForce) {
  14240. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14241. return;
  14242. }
  14243. this._currentEffect = null;
  14244. this._viewportCached.x = 0;
  14245. this._viewportCached.y = 0;
  14246. this._viewportCached.z = 0;
  14247. this._viewportCached.w = 0;
  14248. if (bruteForce) {
  14249. this.resetTextureCache();
  14250. this._currentProgram = null;
  14251. this._stencilState.reset();
  14252. this._depthCullingState.reset();
  14253. this.setDepthFunctionToLessOrEqual();
  14254. this._alphaState.reset();
  14255. this._unpackFlipYCached = null;
  14256. }
  14257. this._resetVertexBufferBinding();
  14258. this._cachedIndexBuffer = null;
  14259. this._cachedEffectForVertexBuffers = null;
  14260. this._unbindVertexArrayObject();
  14261. this.bindIndexBuffer(null);
  14262. };
  14263. /**
  14264. * Set the compressed texture format to use, based on the formats you have, and the formats
  14265. * supported by the hardware / browser.
  14266. *
  14267. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14268. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14269. * to API arguments needed to compressed textures. This puts the burden on the container
  14270. * generator to house the arcane code for determining these for current & future formats.
  14271. *
  14272. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14273. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14274. *
  14275. * Note: The result of this call is not taken into account when a texture is base64.
  14276. *
  14277. * @param formatsAvailable defines the list of those format families you have created
  14278. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14279. *
  14280. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14281. * @returns The extension selected.
  14282. */
  14283. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14284. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14285. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14286. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14287. return this._textureFormatInUse = this._texturesSupported[i];
  14288. }
  14289. }
  14290. }
  14291. // actively set format to nothing, to allow this to be called more than once
  14292. // and possibly fail the 2nd time
  14293. this._textureFormatInUse = null;
  14294. return null;
  14295. };
  14296. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14297. var gl = this._gl;
  14298. var magFilter = gl.NEAREST;
  14299. var minFilter = gl.NEAREST;
  14300. switch (samplingMode) {
  14301. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14302. magFilter = gl.LINEAR;
  14303. if (generateMipMaps) {
  14304. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14305. }
  14306. else {
  14307. minFilter = gl.LINEAR;
  14308. }
  14309. break;
  14310. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14311. magFilter = gl.LINEAR;
  14312. if (generateMipMaps) {
  14313. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14314. }
  14315. else {
  14316. minFilter = gl.LINEAR;
  14317. }
  14318. break;
  14319. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14320. magFilter = gl.NEAREST;
  14321. if (generateMipMaps) {
  14322. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14323. }
  14324. else {
  14325. minFilter = gl.NEAREST;
  14326. }
  14327. break;
  14328. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14329. magFilter = gl.NEAREST;
  14330. if (generateMipMaps) {
  14331. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14332. }
  14333. else {
  14334. minFilter = gl.NEAREST;
  14335. }
  14336. break;
  14337. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14338. magFilter = gl.NEAREST;
  14339. if (generateMipMaps) {
  14340. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14341. }
  14342. else {
  14343. minFilter = gl.LINEAR;
  14344. }
  14345. break;
  14346. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14347. magFilter = gl.NEAREST;
  14348. if (generateMipMaps) {
  14349. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14350. }
  14351. else {
  14352. minFilter = gl.LINEAR;
  14353. }
  14354. break;
  14355. case Engine.TEXTURE_NEAREST_LINEAR:
  14356. magFilter = gl.NEAREST;
  14357. minFilter = gl.LINEAR;
  14358. break;
  14359. case Engine.TEXTURE_NEAREST_NEAREST:
  14360. magFilter = gl.NEAREST;
  14361. minFilter = gl.NEAREST;
  14362. break;
  14363. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14364. magFilter = gl.LINEAR;
  14365. if (generateMipMaps) {
  14366. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14367. }
  14368. else {
  14369. minFilter = gl.NEAREST;
  14370. }
  14371. break;
  14372. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14373. magFilter = gl.LINEAR;
  14374. if (generateMipMaps) {
  14375. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14376. }
  14377. else {
  14378. minFilter = gl.NEAREST;
  14379. }
  14380. break;
  14381. case Engine.TEXTURE_LINEAR_LINEAR:
  14382. magFilter = gl.LINEAR;
  14383. minFilter = gl.LINEAR;
  14384. break;
  14385. case Engine.TEXTURE_LINEAR_NEAREST:
  14386. magFilter = gl.LINEAR;
  14387. minFilter = gl.NEAREST;
  14388. break;
  14389. }
  14390. return {
  14391. min: minFilter,
  14392. mag: magFilter
  14393. };
  14394. };
  14395. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14396. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14397. var img;
  14398. var onload = function () {
  14399. loadedImages[index] = img;
  14400. loadedImages._internalCount++;
  14401. if (scene) {
  14402. scene._removePendingData(img);
  14403. }
  14404. if (loadedImages._internalCount === 6) {
  14405. onfinish(loadedImages);
  14406. }
  14407. };
  14408. var onerror = function (message, exception) {
  14409. if (scene) {
  14410. scene._removePendingData(img);
  14411. }
  14412. if (onErrorCallBack) {
  14413. onErrorCallBack(message, exception);
  14414. }
  14415. };
  14416. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14417. if (scene) {
  14418. scene._addPendingData(img);
  14419. }
  14420. };
  14421. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14422. if (onError === void 0) { onError = null; }
  14423. var loadedImages = [];
  14424. loadedImages._internalCount = 0;
  14425. for (var index = 0; index < 6; index++) {
  14426. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14427. }
  14428. };
  14429. ;
  14430. /** @hidden */
  14431. Engine.prototype._createTexture = function () {
  14432. var texture = this._gl.createTexture();
  14433. if (!texture) {
  14434. throw new Error("Unable to create texture");
  14435. }
  14436. return texture;
  14437. };
  14438. /**
  14439. * Usually called from BABYLON.Texture.ts.
  14440. * Passed information to create a WebGLTexture
  14441. * @param urlArg defines a value which contains one of the following:
  14442. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14443. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14444. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14445. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14446. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14447. * @param scene needed for loading to the correct scene
  14448. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14449. * @param onLoad optional callback to be called upon successful completion
  14450. * @param onError optional callback to be called upon failure
  14451. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14452. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14453. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14454. * @param forcedExtension defines the extension to use to pick the right loader
  14455. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14456. */
  14457. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14458. var _this = this;
  14459. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14460. if (onLoad === void 0) { onLoad = null; }
  14461. if (onError === void 0) { onError = null; }
  14462. if (buffer === void 0) { buffer = null; }
  14463. if (fallback === void 0) { fallback = null; }
  14464. if (format === void 0) { format = null; }
  14465. if (forcedExtension === void 0) { forcedExtension = null; }
  14466. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14467. var fromData = url.substr(0, 5) === "data:";
  14468. var fromBlob = url.substr(0, 5) === "blob:";
  14469. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14470. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14471. // establish the file extension, if possible
  14472. var lastDot = url.lastIndexOf('.');
  14473. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14474. var loader = null;
  14475. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14476. var availableLoader = _a[_i];
  14477. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14478. loader = availableLoader;
  14479. break;
  14480. }
  14481. }
  14482. if (loader) {
  14483. url = loader.transformUrl(url, this._textureFormatInUse);
  14484. }
  14485. if (scene) {
  14486. scene._addPendingData(texture);
  14487. }
  14488. texture.url = url;
  14489. texture.generateMipMaps = !noMipmap;
  14490. texture.samplingMode = samplingMode;
  14491. texture.invertY = invertY;
  14492. if (!this._doNotHandleContextLost) {
  14493. // Keep a link to the buffer only if we plan to handle context lost
  14494. texture._buffer = buffer;
  14495. }
  14496. var onLoadObserver = null;
  14497. if (onLoad && !fallback) {
  14498. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14499. }
  14500. if (!fallback)
  14501. this._internalTexturesCache.push(texture);
  14502. var onInternalError = function (message, exception) {
  14503. if (scene) {
  14504. scene._removePendingData(texture);
  14505. }
  14506. var customFallback = false;
  14507. if (loader) {
  14508. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14509. if (fallbackUrl) {
  14510. // Add Back
  14511. customFallback = true;
  14512. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14513. }
  14514. }
  14515. if (!customFallback) {
  14516. if (onLoadObserver) {
  14517. texture.onLoadedObservable.remove(onLoadObserver);
  14518. }
  14519. if (BABYLON.Tools.UseFallbackTexture) {
  14520. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14521. }
  14522. }
  14523. if (onError) {
  14524. onError(message || "Unknown error", exception);
  14525. }
  14526. };
  14527. // processing for non-image formats
  14528. if (loader) {
  14529. var callback = function (data) {
  14530. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14531. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14532. done();
  14533. return false;
  14534. }, samplingMode);
  14535. });
  14536. };
  14537. if (!buffer) {
  14538. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14539. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14540. });
  14541. }
  14542. else {
  14543. callback(buffer);
  14544. }
  14545. }
  14546. else {
  14547. var onload = function (img) {
  14548. if (fromBlob && !_this._doNotHandleContextLost) {
  14549. // We need to store the image if we need to rebuild the texture
  14550. // in case of a webgl context lost
  14551. texture._buffer = img;
  14552. }
  14553. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14554. var gl = _this._gl;
  14555. var isPot = (img.width === potWidth && img.height === potHeight);
  14556. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14557. if (isPot) {
  14558. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14559. return false;
  14560. }
  14561. var maxTextureSize = _this._caps.maxTextureSize;
  14562. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14563. _this._prepareWorkingCanvas();
  14564. if (!_this._workingCanvas || !_this._workingContext) {
  14565. return false;
  14566. }
  14567. _this._workingCanvas.width = potWidth;
  14568. _this._workingCanvas.height = potHeight;
  14569. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14570. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14571. texture.width = potWidth;
  14572. texture.height = potHeight;
  14573. return false;
  14574. }
  14575. else {
  14576. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14577. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14578. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14579. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14583. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14584. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14585. _this._releaseTexture(source_1);
  14586. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14587. continuationCallback();
  14588. });
  14589. }
  14590. return true;
  14591. }, samplingMode);
  14592. };
  14593. if (!fromData || isBase64) {
  14594. if (buffer instanceof HTMLImageElement) {
  14595. onload(buffer);
  14596. }
  14597. else {
  14598. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14599. }
  14600. }
  14601. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14602. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14603. }
  14604. else {
  14605. onload(buffer);
  14606. }
  14607. }
  14608. return texture;
  14609. };
  14610. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14611. var _this = this;
  14612. var rtt = this.createRenderTargetTexture({
  14613. width: destination.width,
  14614. height: destination.height,
  14615. }, {
  14616. generateMipMaps: false,
  14617. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14618. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14619. generateDepthBuffer: false,
  14620. generateStencilBuffer: false
  14621. });
  14622. if (!this._rescalePostProcess) {
  14623. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14624. }
  14625. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14626. _this._rescalePostProcess.onApply = function (effect) {
  14627. effect._bindTexture("textureSampler", source);
  14628. };
  14629. var hostingScene = scene;
  14630. if (!hostingScene) {
  14631. hostingScene = _this.scenes[_this.scenes.length - 1];
  14632. }
  14633. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14634. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14635. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14636. _this.unBindFramebuffer(rtt);
  14637. _this._releaseTexture(rtt);
  14638. if (onComplete) {
  14639. onComplete();
  14640. }
  14641. });
  14642. };
  14643. /**
  14644. * Update a raw texture
  14645. * @param texture defines the texture to update
  14646. * @param data defines the data to store in the texture
  14647. * @param format defines the format of the data
  14648. * @param invertY defines if data must be stored with Y axis inverted
  14649. * @param compression defines the compression used (null by default)
  14650. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14651. */
  14652. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14653. if (compression === void 0) { compression = null; }
  14654. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14655. if (!texture) {
  14656. return;
  14657. }
  14658. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14659. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14660. // babylon's internalFormat but gl's texImage2D format
  14661. var internalFormat = this._getInternalFormat(format);
  14662. var textureType = this._getWebGLTextureType(type);
  14663. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14664. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14665. if (!this._doNotHandleContextLost) {
  14666. texture._bufferView = data;
  14667. texture.format = format;
  14668. texture.type = type;
  14669. texture.invertY = invertY;
  14670. texture._compression = compression;
  14671. }
  14672. if (texture.width % 4 !== 0) {
  14673. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14674. }
  14675. if (compression && data) {
  14676. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14677. }
  14678. else {
  14679. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14680. }
  14681. if (texture.generateMipMaps) {
  14682. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14683. }
  14684. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14685. // this.resetTextureCache();
  14686. texture.isReady = true;
  14687. };
  14688. /**
  14689. * Creates a raw texture
  14690. * @param data defines the data to store in the texture
  14691. * @param width defines the width of the texture
  14692. * @param height defines the height of the texture
  14693. * @param format defines the format of the data
  14694. * @param generateMipMaps defines if the engine should generate the mip levels
  14695. * @param invertY defines if data must be stored with Y axis inverted
  14696. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14697. * @param compression defines the compression used (null by default)
  14698. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14699. * @returns the raw texture inside an InternalTexture
  14700. */
  14701. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14702. if (compression === void 0) { compression = null; }
  14703. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14704. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14705. texture.baseWidth = width;
  14706. texture.baseHeight = height;
  14707. texture.width = width;
  14708. texture.height = height;
  14709. texture.format = format;
  14710. texture.generateMipMaps = generateMipMaps;
  14711. texture.samplingMode = samplingMode;
  14712. texture.invertY = invertY;
  14713. texture._compression = compression;
  14714. texture.type = type;
  14715. if (!this._doNotHandleContextLost) {
  14716. texture._bufferView = data;
  14717. }
  14718. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14719. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14720. // Filters
  14721. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14722. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14723. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14724. if (generateMipMaps) {
  14725. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14726. }
  14727. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14728. this._internalTexturesCache.push(texture);
  14729. return texture;
  14730. };
  14731. /** @hidden */
  14732. Engine.prototype._unpackFlipY = function (value) {
  14733. if (this._unpackFlipYCached !== value) {
  14734. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14735. if (this.enableUnpackFlipYCached) {
  14736. this._unpackFlipYCached = value;
  14737. }
  14738. }
  14739. };
  14740. /** @hidden */
  14741. Engine.prototype._getUnpackAlignement = function () {
  14742. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14743. };
  14744. /**
  14745. * Creates a dynamic texture
  14746. * @param width defines the width of the texture
  14747. * @param height defines the height of the texture
  14748. * @param generateMipMaps defines if the engine should generate the mip levels
  14749. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14750. * @returns the dynamic texture inside an InternalTexture
  14751. */
  14752. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14753. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14754. texture.baseWidth = width;
  14755. texture.baseHeight = height;
  14756. if (generateMipMaps) {
  14757. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14758. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14759. }
  14760. // this.resetTextureCache();
  14761. texture.width = width;
  14762. texture.height = height;
  14763. texture.isReady = false;
  14764. texture.generateMipMaps = generateMipMaps;
  14765. texture.samplingMode = samplingMode;
  14766. this.updateTextureSamplingMode(samplingMode, texture);
  14767. this._internalTexturesCache.push(texture);
  14768. return texture;
  14769. };
  14770. /**
  14771. * Update the sampling mode of a given texture
  14772. * @param samplingMode defines the required sampling mode
  14773. * @param texture defines the texture to update
  14774. */
  14775. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14776. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14777. if (texture.isCube) {
  14778. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14779. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14781. }
  14782. else if (texture.is3D) {
  14783. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14784. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14785. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14786. }
  14787. else {
  14788. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14789. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14791. }
  14792. texture.samplingMode = samplingMode;
  14793. };
  14794. /**
  14795. * Update the content of a dynamic texture
  14796. * @param texture defines the texture to update
  14797. * @param canvas defines the canvas containing the source
  14798. * @param invertY defines if data must be stored with Y axis inverted
  14799. * @param premulAlpha defines if alpha is stored as premultiplied
  14800. * @param format defines the format of the data
  14801. */
  14802. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14803. if (premulAlpha === void 0) { premulAlpha = false; }
  14804. if (!texture) {
  14805. return;
  14806. }
  14807. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14808. this._unpackFlipY(invertY);
  14809. if (premulAlpha) {
  14810. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14811. }
  14812. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14813. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14814. if (texture.generateMipMaps) {
  14815. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14816. }
  14817. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14818. if (premulAlpha) {
  14819. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14820. }
  14821. texture.isReady = true;
  14822. };
  14823. /**
  14824. * Update a video texture
  14825. * @param texture defines the texture to update
  14826. * @param video defines the video element to use
  14827. * @param invertY defines if data must be stored with Y axis inverted
  14828. */
  14829. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14830. if (!texture || texture._isDisabled) {
  14831. return;
  14832. }
  14833. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14834. this._unpackFlipY(!invertY); // Video are upside down by default
  14835. try {
  14836. // Testing video texture support
  14837. if (this._videoTextureSupported === undefined) {
  14838. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14839. if (this._gl.getError() !== 0) {
  14840. this._videoTextureSupported = false;
  14841. }
  14842. else {
  14843. this._videoTextureSupported = true;
  14844. }
  14845. }
  14846. // Copy video through the current working canvas if video texture is not supported
  14847. if (!this._videoTextureSupported) {
  14848. if (!texture._workingCanvas) {
  14849. texture._workingCanvas = document.createElement("canvas");
  14850. var context = texture._workingCanvas.getContext("2d");
  14851. if (!context) {
  14852. throw new Error("Unable to get 2d context");
  14853. }
  14854. texture._workingContext = context;
  14855. texture._workingCanvas.width = texture.width;
  14856. texture._workingCanvas.height = texture.height;
  14857. }
  14858. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14859. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14860. }
  14861. else {
  14862. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14863. }
  14864. if (texture.generateMipMaps) {
  14865. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14866. }
  14867. if (!wasPreviouslyBound) {
  14868. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14869. }
  14870. // this.resetTextureCache();
  14871. texture.isReady = true;
  14872. }
  14873. catch (ex) {
  14874. // Something unexpected
  14875. // Let's disable the texture
  14876. texture._isDisabled = true;
  14877. }
  14878. };
  14879. /**
  14880. * Updates a depth texture Comparison Mode and Function.
  14881. * If the comparison Function is equal to 0, the mode will be set to none.
  14882. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14883. * @param texture The texture to set the comparison function for
  14884. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14885. */
  14886. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14887. if (this.webGLVersion === 1) {
  14888. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14889. return;
  14890. }
  14891. var gl = this._gl;
  14892. if (texture.isCube) {
  14893. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14894. if (comparisonFunction === 0) {
  14895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14897. }
  14898. else {
  14899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14901. }
  14902. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14903. }
  14904. else {
  14905. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14906. if (comparisonFunction === 0) {
  14907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14909. }
  14910. else {
  14911. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14913. }
  14914. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14915. }
  14916. texture._comparisonFunction = comparisonFunction;
  14917. };
  14918. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14919. var width = size.width || size;
  14920. var height = size.height || size;
  14921. internalTexture.baseWidth = width;
  14922. internalTexture.baseHeight = height;
  14923. internalTexture.width = width;
  14924. internalTexture.height = height;
  14925. internalTexture.isReady = true;
  14926. internalTexture.samples = 1;
  14927. internalTexture.generateMipMaps = false;
  14928. internalTexture._generateDepthBuffer = true;
  14929. internalTexture._generateStencilBuffer = generateStencil;
  14930. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14931. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14932. internalTexture._comparisonFunction = comparisonFunction;
  14933. var gl = this._gl;
  14934. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14935. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14936. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14937. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14938. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14939. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14940. if (comparisonFunction === 0) {
  14941. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14942. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14943. }
  14944. else {
  14945. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14946. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14947. }
  14948. };
  14949. /**
  14950. * Creates a depth stencil texture.
  14951. * This is only available in WebGL 2 or with the depth texture extension available.
  14952. * @param size The size of face edge in the texture.
  14953. * @param options The options defining the texture.
  14954. * @returns The texture
  14955. */
  14956. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14957. if (options.isCube) {
  14958. var width = size.width || size;
  14959. return this._createDepthStencilCubeTexture(width, options);
  14960. }
  14961. else {
  14962. return this._createDepthStencilTexture(size, options);
  14963. }
  14964. };
  14965. /**
  14966. * Creates a depth stencil texture.
  14967. * This is only available in WebGL 2 or with the depth texture extension available.
  14968. * @param size The size of face edge in the texture.
  14969. * @param options The options defining the texture.
  14970. * @returns The texture
  14971. */
  14972. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14973. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14974. if (!this._caps.depthTextureExtension) {
  14975. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14976. return internalTexture;
  14977. }
  14978. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14979. var gl = this._gl;
  14980. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14981. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14982. if (this.webGLVersion > 1) {
  14983. if (internalOptions.generateStencil) {
  14984. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14985. }
  14986. else {
  14987. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14988. }
  14989. }
  14990. else {
  14991. if (internalOptions.generateStencil) {
  14992. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14993. }
  14994. else {
  14995. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14996. }
  14997. }
  14998. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14999. return internalTexture;
  15000. };
  15001. /**
  15002. * Creates a depth stencil cube texture.
  15003. * This is only available in WebGL 2.
  15004. * @param size The size of face edge in the cube texture.
  15005. * @param options The options defining the cube texture.
  15006. * @returns The cube texture
  15007. */
  15008. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15009. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15010. internalTexture.isCube = true;
  15011. if (this.webGLVersion === 1) {
  15012. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15013. return internalTexture;
  15014. }
  15015. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15016. var gl = this._gl;
  15017. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15018. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15019. // Create the depth/stencil buffer
  15020. for (var face = 0; face < 6; face++) {
  15021. if (internalOptions.generateStencil) {
  15022. 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);
  15023. }
  15024. else {
  15025. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15026. }
  15027. }
  15028. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15029. return internalTexture;
  15030. };
  15031. /**
  15032. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15033. * @param renderTarget The render target to set the frame buffer for
  15034. */
  15035. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15036. // Create the framebuffer
  15037. var internalTexture = renderTarget.getInternalTexture();
  15038. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15039. return;
  15040. }
  15041. var gl = this._gl;
  15042. var depthStencilTexture = renderTarget.depthStencilTexture;
  15043. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15044. if (depthStencilTexture.isCube) {
  15045. if (depthStencilTexture._generateStencilBuffer) {
  15046. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15047. }
  15048. else {
  15049. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15050. }
  15051. }
  15052. else {
  15053. if (depthStencilTexture._generateStencilBuffer) {
  15054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15055. }
  15056. else {
  15057. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15058. }
  15059. }
  15060. this.bindUnboundFramebuffer(null);
  15061. };
  15062. /**
  15063. * Creates a new render target texture
  15064. * @param size defines the size of the texture
  15065. * @param options defines the options used to create the texture
  15066. * @returns a new render target texture stored in an InternalTexture
  15067. */
  15068. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15069. var fullOptions = new RenderTargetCreationOptions();
  15070. if (options !== undefined && typeof options === "object") {
  15071. fullOptions.generateMipMaps = options.generateMipMaps;
  15072. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15073. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15074. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15075. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15076. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15077. }
  15078. else {
  15079. fullOptions.generateMipMaps = options;
  15080. fullOptions.generateDepthBuffer = true;
  15081. fullOptions.generateStencilBuffer = false;
  15082. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15083. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15084. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15085. }
  15086. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15087. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15088. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15089. }
  15090. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15091. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15092. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15093. }
  15094. var gl = this._gl;
  15095. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15096. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15097. var width = size.width || size;
  15098. var height = size.height || size;
  15099. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15100. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15101. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15102. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15103. }
  15104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15108. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15109. // Create the framebuffer
  15110. var currentFrameBuffer = this._currentFramebuffer;
  15111. var framebuffer = gl.createFramebuffer();
  15112. this.bindUnboundFramebuffer(framebuffer);
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15114. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15115. if (fullOptions.generateMipMaps) {
  15116. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15117. }
  15118. // Unbind
  15119. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15120. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15121. this.bindUnboundFramebuffer(currentFrameBuffer);
  15122. texture._framebuffer = framebuffer;
  15123. texture.baseWidth = width;
  15124. texture.baseHeight = height;
  15125. texture.width = width;
  15126. texture.height = height;
  15127. texture.isReady = true;
  15128. texture.samples = 1;
  15129. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15130. texture.samplingMode = fullOptions.samplingMode;
  15131. texture.type = fullOptions.type;
  15132. texture.format = fullOptions.format;
  15133. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15134. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15135. // this.resetTextureCache();
  15136. this._internalTexturesCache.push(texture);
  15137. return texture;
  15138. };
  15139. /**
  15140. * Create a multi render target texture
  15141. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15142. * @param size defines the size of the texture
  15143. * @param options defines the creation options
  15144. * @returns the cube texture as an InternalTexture
  15145. */
  15146. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15147. var generateMipMaps = false;
  15148. var generateDepthBuffer = true;
  15149. var generateStencilBuffer = false;
  15150. var generateDepthTexture = false;
  15151. var textureCount = 1;
  15152. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15153. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15154. var types = new Array();
  15155. var samplingModes = new Array();
  15156. if (options !== undefined) {
  15157. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15158. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15159. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15160. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15161. textureCount = options.textureCount || 1;
  15162. if (options.types) {
  15163. types = options.types;
  15164. }
  15165. if (options.samplingModes) {
  15166. samplingModes = options.samplingModes;
  15167. }
  15168. }
  15169. var gl = this._gl;
  15170. // Create the framebuffer
  15171. var framebuffer = gl.createFramebuffer();
  15172. this.bindUnboundFramebuffer(framebuffer);
  15173. var width = size.width || size;
  15174. var height = size.height || size;
  15175. var textures = [];
  15176. var attachments = [];
  15177. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15178. for (var i = 0; i < textureCount; i++) {
  15179. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15180. var type = types[i] || defaultType;
  15181. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15182. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15183. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15184. }
  15185. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15186. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15187. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15188. }
  15189. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15190. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15191. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15192. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15193. }
  15194. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15195. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15196. textures.push(texture);
  15197. attachments.push(attachment);
  15198. gl.activeTexture(gl["TEXTURE" + i]);
  15199. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15204. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15205. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15206. if (generateMipMaps) {
  15207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15208. }
  15209. // Unbind
  15210. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15211. texture._framebuffer = framebuffer;
  15212. texture._depthStencilBuffer = depthStencilBuffer;
  15213. texture.baseWidth = width;
  15214. texture.baseHeight = height;
  15215. texture.width = width;
  15216. texture.height = height;
  15217. texture.isReady = true;
  15218. texture.samples = 1;
  15219. texture.generateMipMaps = generateMipMaps;
  15220. texture.samplingMode = samplingMode;
  15221. texture.type = type;
  15222. texture._generateDepthBuffer = generateDepthBuffer;
  15223. texture._generateStencilBuffer = generateStencilBuffer;
  15224. texture._attachments = attachments;
  15225. this._internalTexturesCache.push(texture);
  15226. }
  15227. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15228. // Depth texture
  15229. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15230. gl.activeTexture(gl.TEXTURE0);
  15231. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15236. 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);
  15237. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15238. depthTexture._framebuffer = framebuffer;
  15239. depthTexture.baseWidth = width;
  15240. depthTexture.baseHeight = height;
  15241. depthTexture.width = width;
  15242. depthTexture.height = height;
  15243. depthTexture.isReady = true;
  15244. depthTexture.samples = 1;
  15245. depthTexture.generateMipMaps = generateMipMaps;
  15246. depthTexture.samplingMode = gl.NEAREST;
  15247. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15248. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15249. textures.push(depthTexture);
  15250. this._internalTexturesCache.push(depthTexture);
  15251. }
  15252. gl.drawBuffers(attachments);
  15253. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15254. this.bindUnboundFramebuffer(null);
  15255. this.resetTextureCache();
  15256. return textures;
  15257. };
  15258. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15259. if (samples === void 0) { samples = 1; }
  15260. var depthStencilBuffer = null;
  15261. var gl = this._gl;
  15262. // Create the depth/stencil buffer
  15263. if (generateStencilBuffer) {
  15264. depthStencilBuffer = gl.createRenderbuffer();
  15265. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15266. if (samples > 1) {
  15267. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15268. }
  15269. else {
  15270. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15271. }
  15272. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15273. }
  15274. else if (generateDepthBuffer) {
  15275. depthStencilBuffer = gl.createRenderbuffer();
  15276. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15277. if (samples > 1) {
  15278. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15279. }
  15280. else {
  15281. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15282. }
  15283. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15284. }
  15285. return depthStencilBuffer;
  15286. };
  15287. /**
  15288. * Updates the sample count of a render target texture
  15289. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15290. * @param texture defines the texture to update
  15291. * @param samples defines the sample count to set
  15292. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15293. */
  15294. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15295. if (this.webGLVersion < 2 || !texture) {
  15296. return 1;
  15297. }
  15298. if (texture.samples === samples) {
  15299. return samples;
  15300. }
  15301. var gl = this._gl;
  15302. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15303. // Dispose previous render buffers
  15304. if (texture._depthStencilBuffer) {
  15305. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15306. texture._depthStencilBuffer = null;
  15307. }
  15308. if (texture._MSAAFramebuffer) {
  15309. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15310. texture._MSAAFramebuffer = null;
  15311. }
  15312. if (texture._MSAARenderBuffer) {
  15313. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15314. texture._MSAARenderBuffer = null;
  15315. }
  15316. if (samples > 1) {
  15317. var framebuffer = gl.createFramebuffer();
  15318. if (!framebuffer) {
  15319. throw new Error("Unable to create multi sampled framebuffer");
  15320. }
  15321. texture._MSAAFramebuffer = framebuffer;
  15322. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15323. var colorRenderbuffer = gl.createRenderbuffer();
  15324. if (!colorRenderbuffer) {
  15325. throw new Error("Unable to create multi sampled framebuffer");
  15326. }
  15327. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15328. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15329. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15330. texture._MSAARenderBuffer = colorRenderbuffer;
  15331. }
  15332. else {
  15333. this.bindUnboundFramebuffer(texture._framebuffer);
  15334. }
  15335. texture.samples = samples;
  15336. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15337. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15338. this.bindUnboundFramebuffer(null);
  15339. return samples;
  15340. };
  15341. /**
  15342. * Update the sample count for a given multiple render target texture
  15343. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15344. * @param textures defines the textures to update
  15345. * @param samples defines the sample count to set
  15346. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15347. */
  15348. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15349. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15350. return 1;
  15351. }
  15352. if (textures[0].samples === samples) {
  15353. return samples;
  15354. }
  15355. var gl = this._gl;
  15356. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15357. // Dispose previous render buffers
  15358. if (textures[0]._depthStencilBuffer) {
  15359. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15360. textures[0]._depthStencilBuffer = null;
  15361. }
  15362. if (textures[0]._MSAAFramebuffer) {
  15363. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15364. textures[0]._MSAAFramebuffer = null;
  15365. }
  15366. for (var i = 0; i < textures.length; i++) {
  15367. if (textures[i]._MSAARenderBuffer) {
  15368. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15369. textures[i]._MSAARenderBuffer = null;
  15370. }
  15371. }
  15372. if (samples > 1) {
  15373. var framebuffer = gl.createFramebuffer();
  15374. if (!framebuffer) {
  15375. throw new Error("Unable to create multi sampled framebuffer");
  15376. }
  15377. this.bindUnboundFramebuffer(framebuffer);
  15378. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15379. var attachments = [];
  15380. for (var i = 0; i < textures.length; i++) {
  15381. var texture = textures[i];
  15382. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15383. var colorRenderbuffer = gl.createRenderbuffer();
  15384. if (!colorRenderbuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15388. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15389. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15390. texture._MSAAFramebuffer = framebuffer;
  15391. texture._MSAARenderBuffer = colorRenderbuffer;
  15392. texture.samples = samples;
  15393. texture._depthStencilBuffer = depthStencilBuffer;
  15394. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15395. attachments.push(attachment);
  15396. }
  15397. gl.drawBuffers(attachments);
  15398. }
  15399. else {
  15400. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15401. }
  15402. this.bindUnboundFramebuffer(null);
  15403. return samples;
  15404. };
  15405. /** @hidden */
  15406. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15407. if (faceIndex === void 0) { faceIndex = 0; }
  15408. if (lod === void 0) { lod = 0; }
  15409. var gl = this._gl;
  15410. var target = gl.TEXTURE_2D;
  15411. if (texture.isCube) {
  15412. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15413. }
  15414. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15415. };
  15416. /** @hidden */
  15417. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15418. if (faceIndex === void 0) { faceIndex = 0; }
  15419. if (lod === void 0) { lod = 0; }
  15420. var gl = this._gl;
  15421. var textureType = this._getWebGLTextureType(texture.type);
  15422. var format = this._getInternalFormat(texture.format);
  15423. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15424. this._unpackFlipY(texture.invertY);
  15425. var target = gl.TEXTURE_2D;
  15426. if (texture.isCube) {
  15427. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15428. }
  15429. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15430. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15431. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15432. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15433. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15434. };
  15435. /** @hidden */
  15436. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15437. if (faceIndex === void 0) { faceIndex = 0; }
  15438. if (lod === void 0) { lod = 0; }
  15439. var gl = this._gl;
  15440. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15441. this._bindTextureDirectly(bindTarget, texture, true);
  15442. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15443. this._bindTextureDirectly(bindTarget, null, true);
  15444. };
  15445. /** @hidden */
  15446. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15447. if (faceIndex === void 0) { faceIndex = 0; }
  15448. if (lod === void 0) { lod = 0; }
  15449. var gl = this._gl;
  15450. var textureType = this._getWebGLTextureType(texture.type);
  15451. var format = this._getInternalFormat(texture.format);
  15452. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15453. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15454. this._bindTextureDirectly(bindTarget, texture, true);
  15455. this._unpackFlipY(texture.invertY);
  15456. var target = gl.TEXTURE_2D;
  15457. if (texture.isCube) {
  15458. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15459. }
  15460. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15461. this._bindTextureDirectly(bindTarget, null, true);
  15462. };
  15463. /**
  15464. * Creates a new render target cube texture
  15465. * @param size defines the size of the texture
  15466. * @param options defines the options used to create the texture
  15467. * @returns a new render target cube texture stored in an InternalTexture
  15468. */
  15469. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15470. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15471. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15472. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15473. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15474. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15475. }
  15476. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15477. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15478. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15479. }
  15480. var gl = this._gl;
  15481. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15482. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15483. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15484. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15485. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15486. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15487. }
  15488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15492. for (var face = 0; face < 6; face++) {
  15493. 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);
  15494. }
  15495. // Create the framebuffer
  15496. var framebuffer = gl.createFramebuffer();
  15497. this.bindUnboundFramebuffer(framebuffer);
  15498. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15499. // MipMaps
  15500. if (fullOptions.generateMipMaps) {
  15501. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15502. }
  15503. // Unbind
  15504. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15505. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15506. this.bindUnboundFramebuffer(null);
  15507. texture._framebuffer = framebuffer;
  15508. texture.width = size;
  15509. texture.height = size;
  15510. texture.isReady = true;
  15511. texture.isCube = true;
  15512. texture.samples = 1;
  15513. texture.generateMipMaps = fullOptions.generateMipMaps;
  15514. texture.samplingMode = fullOptions.samplingMode;
  15515. texture.type = fullOptions.type;
  15516. texture.format = fullOptions.format;
  15517. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15518. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15519. this._internalTexturesCache.push(texture);
  15520. return texture;
  15521. };
  15522. /**
  15523. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15524. * @param rootUrl defines the url where the file to load is located
  15525. * @param scene defines the current scene
  15526. * @param lodScale defines scale to apply to the mip map selection
  15527. * @param lodOffset defines offset to apply to the mip map selection
  15528. * @param onLoad defines an optional callback raised when the texture is loaded
  15529. * @param onError defines an optional callback raised if there is an issue to load the texture
  15530. * @param format defines the format of the data
  15531. * @param forcedExtension defines the extension to use to pick the right loader
  15532. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15533. * @returns the cube texture as an InternalTexture
  15534. */
  15535. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15536. var _this = this;
  15537. if (onLoad === void 0) { onLoad = null; }
  15538. if (onError === void 0) { onError = null; }
  15539. if (forcedExtension === void 0) { forcedExtension = null; }
  15540. if (createPolynomials === void 0) { createPolynomials = true; }
  15541. var callback = function (loadData) {
  15542. if (!loadData) {
  15543. if (onLoad) {
  15544. onLoad(null);
  15545. }
  15546. return;
  15547. }
  15548. var texture = loadData.texture;
  15549. if (!createPolynomials) {
  15550. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15551. }
  15552. else if (loadData.info.sphericalPolynomial) {
  15553. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15554. }
  15555. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15556. if (_this._caps.textureLOD) {
  15557. // Do not add extra process if texture lod is supported.
  15558. if (onLoad) {
  15559. onLoad(texture);
  15560. }
  15561. return;
  15562. }
  15563. var mipSlices = 3;
  15564. var gl = _this._gl;
  15565. var width = loadData.width;
  15566. if (!width) {
  15567. return;
  15568. }
  15569. var textures = [];
  15570. for (var i = 0; i < mipSlices; i++) {
  15571. //compute LOD from even spacing in smoothness (matching shader calculation)
  15572. var smoothness = i / (mipSlices - 1);
  15573. var roughness = 1 - smoothness;
  15574. var minLODIndex = lodOffset; // roughness = 0
  15575. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15576. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15577. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15578. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15579. glTextureFromLod.type = texture.type;
  15580. glTextureFromLod.format = texture.format;
  15581. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15582. glTextureFromLod.height = glTextureFromLod.width;
  15583. glTextureFromLod.isCube = true;
  15584. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15589. if (loadData.isDDS) {
  15590. var info = loadData.info;
  15591. var data = loadData.data;
  15592. _this._unpackFlipY(info.isCompressed);
  15593. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15594. }
  15595. else {
  15596. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15597. }
  15598. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15599. // Wrap in a base texture for easy binding.
  15600. var lodTexture = new BABYLON.BaseTexture(scene);
  15601. lodTexture.isCube = true;
  15602. lodTexture._texture = glTextureFromLod;
  15603. glTextureFromLod.isReady = true;
  15604. textures.push(lodTexture);
  15605. }
  15606. texture._lodTextureHigh = textures[2];
  15607. texture._lodTextureMid = textures[1];
  15608. texture._lodTextureLow = textures[0];
  15609. if (onLoad) {
  15610. onLoad(texture);
  15611. }
  15612. };
  15613. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15614. };
  15615. /**
  15616. * Creates a cube texture
  15617. * @param rootUrl defines the url where the files to load is located
  15618. * @param scene defines the current scene
  15619. * @param files defines the list of files to load (1 per face)
  15620. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15621. * @param onLoad defines an optional callback raised when the texture is loaded
  15622. * @param onError defines an optional callback raised if there is an issue to load the texture
  15623. * @param format defines the format of the data
  15624. * @param forcedExtension defines the extension to use to pick the right loader
  15625. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15626. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15627. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15628. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15629. * @returns the cube texture as an InternalTexture
  15630. */
  15631. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15632. var _this = this;
  15633. if (onLoad === void 0) { onLoad = null; }
  15634. if (onError === void 0) { onError = null; }
  15635. if (forcedExtension === void 0) { forcedExtension = null; }
  15636. if (createPolynomials === void 0) { createPolynomials = false; }
  15637. if (lodScale === void 0) { lodScale = 0; }
  15638. if (lodOffset === void 0) { lodOffset = 0; }
  15639. if (fallback === void 0) { fallback = null; }
  15640. var gl = this._gl;
  15641. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15642. texture.isCube = true;
  15643. texture.url = rootUrl;
  15644. texture.generateMipMaps = !noMipmap;
  15645. texture._lodGenerationScale = lodScale;
  15646. texture._lodGenerationOffset = lodOffset;
  15647. if (!this._doNotHandleContextLost) {
  15648. texture._extension = forcedExtension;
  15649. texture._files = files;
  15650. }
  15651. var lastDot = rootUrl.lastIndexOf('.');
  15652. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15653. var loader = null;
  15654. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15655. var availableLoader = _a[_i];
  15656. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15657. loader = availableLoader;
  15658. break;
  15659. }
  15660. }
  15661. var onInternalError = function (request, exception) {
  15662. if (loader) {
  15663. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15664. if (fallbackUrl) {
  15665. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15666. }
  15667. }
  15668. if (onError && request) {
  15669. onError(request.status + " " + request.statusText, exception);
  15670. }
  15671. };
  15672. if (loader) {
  15673. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15674. var onloaddata = function (data) {
  15675. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15676. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15677. };
  15678. if (files && files.length === 6) {
  15679. if (loader.supportCascades) {
  15680. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15681. }
  15682. else if (onError) {
  15683. onError("Textures type does not support cascades.");
  15684. }
  15685. }
  15686. else {
  15687. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15688. }
  15689. }
  15690. else {
  15691. if (!files) {
  15692. throw new Error("Cannot load cubemap because files were not defined");
  15693. }
  15694. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15695. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15696. var height = width;
  15697. _this._prepareWorkingCanvas();
  15698. if (!_this._workingCanvas || !_this._workingContext) {
  15699. return;
  15700. }
  15701. _this._workingCanvas.width = width;
  15702. _this._workingCanvas.height = height;
  15703. var faces = [
  15704. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15705. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15706. ];
  15707. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15708. _this._unpackFlipY(false);
  15709. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15710. for (var index = 0; index < faces.length; index++) {
  15711. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15712. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15713. }
  15714. if (!noMipmap) {
  15715. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15716. }
  15717. _this._setCubeMapTextureParams(!noMipmap);
  15718. texture.width = width;
  15719. texture.height = height;
  15720. texture.isReady = true;
  15721. if (format) {
  15722. texture.format = format;
  15723. }
  15724. texture.onLoadedObservable.notifyObservers(texture);
  15725. texture.onLoadedObservable.clear();
  15726. if (onLoad) {
  15727. onLoad();
  15728. }
  15729. }, files, onError);
  15730. }
  15731. this._internalTexturesCache.push(texture);
  15732. return texture;
  15733. };
  15734. /**
  15735. * @hidden
  15736. */
  15737. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15738. var gl = this._gl;
  15739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15740. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15741. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15743. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15744. // this.resetTextureCache();
  15745. };
  15746. /**
  15747. * Update a raw cube texture
  15748. * @param texture defines the texture to udpdate
  15749. * @param data defines the data to store
  15750. * @param format defines the data format
  15751. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15752. * @param invertY defines if data must be stored with Y axis inverted
  15753. * @param compression defines the compression used (null by default)
  15754. * @param level defines which level of the texture to update
  15755. */
  15756. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15757. if (compression === void 0) { compression = null; }
  15758. if (level === void 0) { level = 0; }
  15759. texture._bufferViewArray = data;
  15760. texture.format = format;
  15761. texture.type = type;
  15762. texture.invertY = invertY;
  15763. texture._compression = compression;
  15764. var gl = this._gl;
  15765. var textureType = this._getWebGLTextureType(type);
  15766. var internalFormat = this._getInternalFormat(format);
  15767. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15768. var needConversion = false;
  15769. if (internalFormat === gl.RGB) {
  15770. internalFormat = gl.RGBA;
  15771. needConversion = true;
  15772. }
  15773. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15774. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15775. if (texture.width % 4 !== 0) {
  15776. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15777. }
  15778. // Data are known to be in +X +Y +Z -X -Y -Z
  15779. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15780. var faceData = data[faceIndex];
  15781. if (compression) {
  15782. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15783. }
  15784. else {
  15785. if (needConversion) {
  15786. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15787. }
  15788. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15789. }
  15790. }
  15791. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15792. if (isPot && texture.generateMipMaps && level === 0) {
  15793. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15794. }
  15795. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15796. // this.resetTextureCache();
  15797. texture.isReady = true;
  15798. };
  15799. /**
  15800. * Creates a new raw cube texture
  15801. * @param data defines the array of data to use to create each face
  15802. * @param size defines the size of the textures
  15803. * @param format defines the format of the data
  15804. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15805. * @param generateMipMaps defines if the engine should generate the mip levels
  15806. * @param invertY defines if data must be stored with Y axis inverted
  15807. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15808. * @param compression defines the compression used (null by default)
  15809. * @returns the cube texture as an InternalTexture
  15810. */
  15811. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15812. if (compression === void 0) { compression = null; }
  15813. var gl = this._gl;
  15814. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15815. texture.isCube = true;
  15816. texture.format = format;
  15817. texture.type = type;
  15818. if (!this._doNotHandleContextLost) {
  15819. texture._bufferViewArray = data;
  15820. }
  15821. var textureType = this._getWebGLTextureType(type);
  15822. var internalFormat = this._getInternalFormat(format);
  15823. if (internalFormat === gl.RGB) {
  15824. internalFormat = gl.RGBA;
  15825. }
  15826. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15827. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15828. generateMipMaps = false;
  15829. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15830. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15831. }
  15832. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15833. generateMipMaps = false;
  15834. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15835. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15836. }
  15837. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15838. generateMipMaps = false;
  15839. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15840. }
  15841. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15842. generateMipMaps = false;
  15843. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15844. }
  15845. var width = size;
  15846. var height = width;
  15847. texture.width = width;
  15848. texture.height = height;
  15849. // Double check on POT to generate Mips.
  15850. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15851. if (!isPot) {
  15852. generateMipMaps = false;
  15853. }
  15854. // Upload data if needed. The texture won't be ready until then.
  15855. if (data) {
  15856. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15857. }
  15858. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15859. // Filters
  15860. if (data && generateMipMaps) {
  15861. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15862. }
  15863. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15868. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15869. texture.generateMipMaps = generateMipMaps;
  15870. return texture;
  15871. };
  15872. /**
  15873. * Creates a new raw cube texture from a specified url
  15874. * @param url defines the url where the data is located
  15875. * @param scene defines the current scene
  15876. * @param size defines the size of the textures
  15877. * @param format defines the format of the data
  15878. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15879. * @param noMipmap defines if the engine should avoid generating the mip levels
  15880. * @param callback defines a callback used to extract texture data from loaded data
  15881. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15882. * @param onLoad defines a callback called when texture is loaded
  15883. * @param onError defines a callback called if there is an error
  15884. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15885. * @param invertY defines if data must be stored with Y axis inverted
  15886. * @returns the cube texture as an InternalTexture
  15887. */
  15888. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15889. var _this = this;
  15890. if (onLoad === void 0) { onLoad = null; }
  15891. if (onError === void 0) { onError = null; }
  15892. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15893. if (invertY === void 0) { invertY = false; }
  15894. var gl = this._gl;
  15895. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15896. scene._addPendingData(texture);
  15897. texture.url = url;
  15898. this._internalTexturesCache.push(texture);
  15899. var onerror = function (request, exception) {
  15900. scene._removePendingData(texture);
  15901. if (onError && request) {
  15902. onError(request.status + " " + request.statusText, exception);
  15903. }
  15904. };
  15905. var internalCallback = function (data) {
  15906. var width = texture.width;
  15907. var faceDataArrays = callback(data);
  15908. if (!faceDataArrays) {
  15909. return;
  15910. }
  15911. if (mipmapGenerator) {
  15912. var textureType = _this._getWebGLTextureType(type);
  15913. var internalFormat = _this._getInternalFormat(format);
  15914. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15915. var needConversion = false;
  15916. if (internalFormat === gl.RGB) {
  15917. internalFormat = gl.RGBA;
  15918. needConversion = true;
  15919. }
  15920. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15921. _this._unpackFlipY(false);
  15922. var mipData = mipmapGenerator(faceDataArrays);
  15923. for (var level = 0; level < mipData.length; level++) {
  15924. var mipSize = width >> level;
  15925. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15926. var mipFaceData = mipData[level][faceIndex];
  15927. if (needConversion) {
  15928. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15929. }
  15930. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15931. }
  15932. }
  15933. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15934. }
  15935. else {
  15936. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15937. }
  15938. texture.isReady = true;
  15939. // this.resetTextureCache();
  15940. scene._removePendingData(texture);
  15941. if (onLoad) {
  15942. onLoad();
  15943. }
  15944. };
  15945. this._loadFile(url, function (data) {
  15946. internalCallback(data);
  15947. }, undefined, scene.database, true, onerror);
  15948. return texture;
  15949. };
  15950. ;
  15951. /**
  15952. * Update a raw 3D texture
  15953. * @param texture defines the texture to update
  15954. * @param data defines the data to store
  15955. * @param format defines the data format
  15956. * @param invertY defines if data must be stored with Y axis inverted
  15957. * @param compression defines the used compression (can be null)
  15958. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15959. */
  15960. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15961. if (compression === void 0) { compression = null; }
  15962. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15963. var internalType = this._getWebGLTextureType(textureType);
  15964. var internalFormat = this._getInternalFormat(format);
  15965. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15966. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15967. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15968. if (!this._doNotHandleContextLost) {
  15969. texture._bufferView = data;
  15970. texture.format = format;
  15971. texture.invertY = invertY;
  15972. texture._compression = compression;
  15973. }
  15974. if (texture.width % 4 !== 0) {
  15975. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15976. }
  15977. if (compression && data) {
  15978. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15979. }
  15980. else {
  15981. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15982. }
  15983. if (texture.generateMipMaps) {
  15984. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15985. }
  15986. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15987. // this.resetTextureCache();
  15988. texture.isReady = true;
  15989. };
  15990. /**
  15991. * Creates a new raw 3D texture
  15992. * @param data defines the data used to create the texture
  15993. * @param width defines the width of the texture
  15994. * @param height defines the height of the texture
  15995. * @param depth defines the depth of the texture
  15996. * @param format defines the format of the texture
  15997. * @param generateMipMaps defines if the engine must generate mip levels
  15998. * @param invertY defines if data must be stored with Y axis inverted
  15999. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16000. * @param compression defines the compressed used (can be null)
  16001. * @param textureType defines the compressed used (can be null)
  16002. * @returns a new raw 3D texture (stored in an InternalTexture)
  16003. */
  16004. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16005. if (compression === void 0) { compression = null; }
  16006. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16007. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16008. texture.baseWidth = width;
  16009. texture.baseHeight = height;
  16010. texture.baseDepth = depth;
  16011. texture.width = width;
  16012. texture.height = height;
  16013. texture.depth = depth;
  16014. texture.format = format;
  16015. texture.type = textureType;
  16016. texture.generateMipMaps = generateMipMaps;
  16017. texture.samplingMode = samplingMode;
  16018. texture.is3D = true;
  16019. if (!this._doNotHandleContextLost) {
  16020. texture._bufferView = data;
  16021. }
  16022. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16023. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16024. // Filters
  16025. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16026. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16027. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16028. if (generateMipMaps) {
  16029. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16030. }
  16031. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16032. this._internalTexturesCache.push(texture);
  16033. return texture;
  16034. };
  16035. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16036. var gl = this._gl;
  16037. if (!gl) {
  16038. return;
  16039. }
  16040. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16042. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16043. if (!noMipmap && !isCompressed) {
  16044. gl.generateMipmap(gl.TEXTURE_2D);
  16045. }
  16046. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16047. // this.resetTextureCache();
  16048. if (scene) {
  16049. scene._removePendingData(texture);
  16050. }
  16051. texture.onLoadedObservable.notifyObservers(texture);
  16052. texture.onLoadedObservable.clear();
  16053. };
  16054. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16055. var _this = this;
  16056. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16057. var maxTextureSize = this.getCaps().maxTextureSize;
  16058. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16059. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16060. var gl = this._gl;
  16061. if (!gl) {
  16062. return;
  16063. }
  16064. if (!texture._webGLTexture) {
  16065. // this.resetTextureCache();
  16066. if (scene) {
  16067. scene._removePendingData(texture);
  16068. }
  16069. return;
  16070. }
  16071. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16072. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16073. texture.baseWidth = width;
  16074. texture.baseHeight = height;
  16075. texture.width = potWidth;
  16076. texture.height = potHeight;
  16077. texture.isReady = true;
  16078. if (processFunction(potWidth, potHeight, function () {
  16079. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16080. })) {
  16081. // Returning as texture needs extra async steps
  16082. return;
  16083. }
  16084. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16085. };
  16086. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16087. // Create new RGBA data container.
  16088. var rgbaData;
  16089. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16090. rgbaData = new Float32Array(width * height * 4);
  16091. }
  16092. else {
  16093. rgbaData = new Uint32Array(width * height * 4);
  16094. }
  16095. // Convert each pixel.
  16096. for (var x = 0; x < width; x++) {
  16097. for (var y = 0; y < height; y++) {
  16098. var index = (y * width + x) * 3;
  16099. var newIndex = (y * width + x) * 4;
  16100. // Map Old Value to new value.
  16101. rgbaData[newIndex + 0] = rgbData[index + 0];
  16102. rgbaData[newIndex + 1] = rgbData[index + 1];
  16103. rgbaData[newIndex + 2] = rgbData[index + 2];
  16104. // Add fully opaque alpha channel.
  16105. rgbaData[newIndex + 3] = 1;
  16106. }
  16107. }
  16108. return rgbaData;
  16109. };
  16110. /** @hidden */
  16111. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16112. var gl = this._gl;
  16113. if (texture._framebuffer) {
  16114. gl.deleteFramebuffer(texture._framebuffer);
  16115. texture._framebuffer = null;
  16116. }
  16117. if (texture._depthStencilBuffer) {
  16118. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16119. texture._depthStencilBuffer = null;
  16120. }
  16121. if (texture._MSAAFramebuffer) {
  16122. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16123. texture._MSAAFramebuffer = null;
  16124. }
  16125. if (texture._MSAARenderBuffer) {
  16126. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16127. texture._MSAARenderBuffer = null;
  16128. }
  16129. };
  16130. /** @hidden */
  16131. Engine.prototype._releaseTexture = function (texture) {
  16132. var gl = this._gl;
  16133. this._releaseFramebufferObjects(texture);
  16134. gl.deleteTexture(texture._webGLTexture);
  16135. // Unbind channels
  16136. this.unbindAllTextures();
  16137. var index = this._internalTexturesCache.indexOf(texture);
  16138. if (index !== -1) {
  16139. this._internalTexturesCache.splice(index, 1);
  16140. }
  16141. // Integrated fixed lod samplers.
  16142. if (texture._lodTextureHigh) {
  16143. texture._lodTextureHigh.dispose();
  16144. }
  16145. if (texture._lodTextureMid) {
  16146. texture._lodTextureMid.dispose();
  16147. }
  16148. if (texture._lodTextureLow) {
  16149. texture._lodTextureLow.dispose();
  16150. }
  16151. // Set output texture of post process to null if the texture has been released/disposed
  16152. this.scenes.forEach(function (scene) {
  16153. scene.postProcesses.forEach(function (postProcess) {
  16154. if (postProcess._outputTexture == texture) {
  16155. postProcess._outputTexture = null;
  16156. }
  16157. });
  16158. scene.cameras.forEach(function (camera) {
  16159. camera._postProcesses.forEach(function (postProcess) {
  16160. if (postProcess) {
  16161. if (postProcess._outputTexture == texture) {
  16162. postProcess._outputTexture = null;
  16163. }
  16164. }
  16165. });
  16166. });
  16167. });
  16168. };
  16169. Engine.prototype.setProgram = function (program) {
  16170. if (this._currentProgram !== program) {
  16171. this._gl.useProgram(program);
  16172. this._currentProgram = program;
  16173. }
  16174. };
  16175. /**
  16176. * Binds an effect to the webGL context
  16177. * @param effect defines the effect to bind
  16178. */
  16179. Engine.prototype.bindSamplers = function (effect) {
  16180. this.setProgram(effect.getProgram());
  16181. var samplers = effect.getSamplers();
  16182. for (var index = 0; index < samplers.length; index++) {
  16183. var uniform = effect.getUniform(samplers[index]);
  16184. if (uniform) {
  16185. this._boundUniforms[index] = uniform;
  16186. }
  16187. }
  16188. this._currentEffect = null;
  16189. };
  16190. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16191. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16192. return;
  16193. }
  16194. // Remove
  16195. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16196. // Bind last to it
  16197. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16198. // Bind to dummy
  16199. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16200. };
  16201. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16202. if (!internalTexture) {
  16203. return -1;
  16204. }
  16205. internalTexture._initialSlot = channel;
  16206. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16207. if (channel !== internalTexture._designatedSlot) {
  16208. this._textureCollisions.addCount(1, false);
  16209. }
  16210. }
  16211. else {
  16212. if (channel !== internalTexture._designatedSlot) {
  16213. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16214. return internalTexture._designatedSlot;
  16215. }
  16216. else {
  16217. // No slot for this texture, let's pick a new one (if we find a free slot)
  16218. if (this._nextFreeTextureSlots.length) {
  16219. return this._nextFreeTextureSlots[0];
  16220. }
  16221. // We need to recycle the oldest bound texture, sorry.
  16222. this._textureCollisions.addCount(1, false);
  16223. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16224. }
  16225. }
  16226. }
  16227. return channel;
  16228. };
  16229. Engine.prototype._linkTrackers = function (previous, next) {
  16230. previous.next = next;
  16231. next.previous = previous;
  16232. };
  16233. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16234. var currentSlot = internalTexture._designatedSlot;
  16235. if (currentSlot === -1) {
  16236. return -1;
  16237. }
  16238. internalTexture._designatedSlot = -1;
  16239. if (this.disableTextureBindingOptimization) {
  16240. return -1;
  16241. }
  16242. // Remove from bound list
  16243. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16244. // Free the slot
  16245. this._boundTexturesCache[currentSlot] = null;
  16246. this._nextFreeTextureSlots.push(currentSlot);
  16247. return currentSlot;
  16248. };
  16249. Engine.prototype._activateCurrentTexture = function () {
  16250. if (this._currentTextureChannel !== this._activeChannel) {
  16251. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16252. this._currentTextureChannel = this._activeChannel;
  16253. }
  16254. };
  16255. /** @hidden */
  16256. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16257. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16258. if (force === void 0) { force = false; }
  16259. var wasPreviouslyBound = false;
  16260. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16261. this._activeChannel = texture._designatedSlot;
  16262. }
  16263. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16264. var isTextureForRendering = texture && texture._initialSlot > -1;
  16265. if (currentTextureBound !== texture || force) {
  16266. if (currentTextureBound) {
  16267. this._removeDesignatedSlot(currentTextureBound);
  16268. }
  16269. this._activateCurrentTexture();
  16270. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16271. this._boundTexturesCache[this._activeChannel] = texture;
  16272. if (texture) {
  16273. if (!this.disableTextureBindingOptimization) {
  16274. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16275. if (slotIndex > -1) {
  16276. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16277. }
  16278. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16279. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16280. }
  16281. texture._designatedSlot = this._activeChannel;
  16282. }
  16283. }
  16284. else if (forTextureDataUpdate) {
  16285. wasPreviouslyBound = true;
  16286. this._activateCurrentTexture();
  16287. }
  16288. if (isTextureForRendering && !forTextureDataUpdate) {
  16289. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16290. }
  16291. return wasPreviouslyBound;
  16292. };
  16293. /** @hidden */
  16294. Engine.prototype._bindTexture = function (channel, texture) {
  16295. if (channel < 0) {
  16296. return;
  16297. }
  16298. if (texture) {
  16299. channel = this._getCorrectTextureChannel(channel, texture);
  16300. }
  16301. this._activeChannel = channel;
  16302. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16303. };
  16304. /**
  16305. * Sets a texture to the webGL context from a postprocess
  16306. * @param channel defines the channel to use
  16307. * @param postProcess defines the source postprocess
  16308. */
  16309. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16310. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16311. };
  16312. /**
  16313. * Binds the output of the passed in post process to the texture channel specified
  16314. * @param channel The channel the texture should be bound to
  16315. * @param postProcess The post process which's output should be bound
  16316. */
  16317. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16318. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16319. };
  16320. /**
  16321. * Unbind all textures from the webGL context
  16322. */
  16323. Engine.prototype.unbindAllTextures = function () {
  16324. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16325. this._activeChannel = channel;
  16326. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16327. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16328. if (this.webGLVersion > 1) {
  16329. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16330. }
  16331. }
  16332. };
  16333. /**
  16334. * Sets a texture to the according uniform.
  16335. * @param channel The texture channel
  16336. * @param uniform The uniform to set
  16337. * @param texture The texture to apply
  16338. */
  16339. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16340. if (channel < 0) {
  16341. return;
  16342. }
  16343. if (uniform) {
  16344. this._boundUniforms[channel] = uniform;
  16345. }
  16346. this._setTexture(channel, texture);
  16347. };
  16348. /**
  16349. * Sets a depth stencil texture from a render target to the according uniform.
  16350. * @param channel The texture channel
  16351. * @param uniform The uniform to set
  16352. * @param texture The render target texture containing the depth stencil texture to apply
  16353. */
  16354. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16355. if (channel < 0) {
  16356. return;
  16357. }
  16358. if (uniform) {
  16359. this._boundUniforms[channel] = uniform;
  16360. }
  16361. if (!texture || !texture.depthStencilTexture) {
  16362. this._setTexture(channel, null);
  16363. }
  16364. else {
  16365. this._setTexture(channel, texture, false, true);
  16366. }
  16367. };
  16368. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16369. var uniform = this._boundUniforms[sourceSlot];
  16370. if (uniform._currentState === destination) {
  16371. return;
  16372. }
  16373. this._gl.uniform1i(uniform, destination);
  16374. uniform._currentState = destination;
  16375. };
  16376. Engine.prototype._getTextureWrapMode = function (mode) {
  16377. switch (mode) {
  16378. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16379. return this._gl.REPEAT;
  16380. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16381. return this._gl.CLAMP_TO_EDGE;
  16382. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16383. return this._gl.MIRRORED_REPEAT;
  16384. }
  16385. return this._gl.REPEAT;
  16386. };
  16387. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16388. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16389. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16390. // Not ready?
  16391. if (!texture) {
  16392. if (this._boundTexturesCache[channel] != null) {
  16393. this._activeChannel = channel;
  16394. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16395. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16396. if (this.webGLVersion > 1) {
  16397. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16398. }
  16399. }
  16400. return false;
  16401. }
  16402. // Video
  16403. if (texture.video) {
  16404. this._activeChannel = channel;
  16405. texture.update();
  16406. }
  16407. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16408. texture.delayLoad();
  16409. return false;
  16410. }
  16411. var internalTexture;
  16412. if (depthStencilTexture) {
  16413. internalTexture = texture.depthStencilTexture;
  16414. }
  16415. else if (texture.isReady()) {
  16416. internalTexture = texture.getInternalTexture();
  16417. }
  16418. else if (texture.isCube) {
  16419. internalTexture = this.emptyCubeTexture;
  16420. }
  16421. else if (texture.is3D) {
  16422. internalTexture = this.emptyTexture3D;
  16423. }
  16424. else {
  16425. internalTexture = this.emptyTexture;
  16426. }
  16427. if (!isPartOfTextureArray) {
  16428. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16429. }
  16430. var needToBind = true;
  16431. if (this._boundTexturesCache[channel] === internalTexture) {
  16432. this._moveBoundTextureOnTop(internalTexture);
  16433. if (!isPartOfTextureArray) {
  16434. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16435. }
  16436. needToBind = false;
  16437. }
  16438. this._activeChannel = channel;
  16439. if (internalTexture && internalTexture.is3D) {
  16440. if (needToBind) {
  16441. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16442. }
  16443. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16444. internalTexture._cachedWrapU = texture.wrapU;
  16445. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16446. }
  16447. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16448. internalTexture._cachedWrapV = texture.wrapV;
  16449. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16450. }
  16451. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16452. internalTexture._cachedWrapR = texture.wrapR;
  16453. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16454. }
  16455. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16456. }
  16457. else if (internalTexture && internalTexture.isCube) {
  16458. if (needToBind) {
  16459. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16460. }
  16461. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16462. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16463. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16464. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16465. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16466. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16467. }
  16468. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16469. }
  16470. else {
  16471. if (needToBind) {
  16472. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16473. }
  16474. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16475. internalTexture._cachedWrapU = texture.wrapU;
  16476. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16477. }
  16478. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16479. internalTexture._cachedWrapV = texture.wrapV;
  16480. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16481. }
  16482. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16483. }
  16484. return true;
  16485. };
  16486. /**
  16487. * Sets an array of texture to the webGL context
  16488. * @param channel defines the channel where the texture array must be set
  16489. * @param uniform defines the associated uniform location
  16490. * @param textures defines the array of textures to bind
  16491. */
  16492. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16493. if (channel < 0 || !uniform) {
  16494. return;
  16495. }
  16496. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16497. this._textureUnits = new Int32Array(textures.length);
  16498. }
  16499. for (var i = 0; i < textures.length; i++) {
  16500. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16501. }
  16502. this._gl.uniform1iv(uniform, this._textureUnits);
  16503. for (var index = 0; index < textures.length; index++) {
  16504. this._setTexture(this._textureUnits[index], textures[index], true);
  16505. }
  16506. };
  16507. /** @hidden */
  16508. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16509. var internalTexture = texture.getInternalTexture();
  16510. if (!internalTexture) {
  16511. return;
  16512. }
  16513. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16514. var value = texture.anisotropicFilteringLevel;
  16515. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16516. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16517. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16518. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16519. }
  16520. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16521. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16522. internalTexture._cachedAnisotropicFilteringLevel = value;
  16523. }
  16524. };
  16525. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16526. this._bindTextureDirectly(target, texture, true, true);
  16527. this._gl.texParameterf(target, parameter, value);
  16528. };
  16529. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16530. if (texture) {
  16531. this._bindTextureDirectly(target, texture, true, true);
  16532. }
  16533. this._gl.texParameteri(target, parameter, value);
  16534. };
  16535. /**
  16536. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16537. * @param x defines the x coordinate of the rectangle where pixels must be read
  16538. * @param y defines the y coordinate of the rectangle where pixels must be read
  16539. * @param width defines the width of the rectangle where pixels must be read
  16540. * @param height defines the height of the rectangle where pixels must be read
  16541. * @returns a Uint8Array containing RGBA colors
  16542. */
  16543. Engine.prototype.readPixels = function (x, y, width, height) {
  16544. var data = new Uint8Array(height * width * 4);
  16545. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16546. return data;
  16547. };
  16548. /**
  16549. * Add an externaly attached data from its key.
  16550. * This method call will fail and return false, if such key already exists.
  16551. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16552. * @param key the unique key that identifies the data
  16553. * @param data the data object to associate to the key for this Engine instance
  16554. * @return true if no such key were already present and the data was added successfully, false otherwise
  16555. */
  16556. Engine.prototype.addExternalData = function (key, data) {
  16557. if (!this._externalData) {
  16558. this._externalData = new BABYLON.StringDictionary();
  16559. }
  16560. return this._externalData.add(key, data);
  16561. };
  16562. /**
  16563. * Get an externaly attached data from its key
  16564. * @param key the unique key that identifies the data
  16565. * @return the associated data, if present (can be null), or undefined if not present
  16566. */
  16567. Engine.prototype.getExternalData = function (key) {
  16568. if (!this._externalData) {
  16569. this._externalData = new BABYLON.StringDictionary();
  16570. }
  16571. return this._externalData.get(key);
  16572. };
  16573. /**
  16574. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16575. * @param key the unique key that identifies the data
  16576. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16577. * @return the associated data, can be null if the factory returned null.
  16578. */
  16579. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16580. if (!this._externalData) {
  16581. this._externalData = new BABYLON.StringDictionary();
  16582. }
  16583. return this._externalData.getOrAddWithFactory(key, factory);
  16584. };
  16585. /**
  16586. * Remove an externaly attached data from the Engine instance
  16587. * @param key the unique key that identifies the data
  16588. * @return true if the data was successfully removed, false if it doesn't exist
  16589. */
  16590. Engine.prototype.removeExternalData = function (key) {
  16591. if (!this._externalData) {
  16592. this._externalData = new BABYLON.StringDictionary();
  16593. }
  16594. return this._externalData.remove(key);
  16595. };
  16596. /**
  16597. * Unbind all vertex attributes from the webGL context
  16598. */
  16599. Engine.prototype.unbindAllAttributes = function () {
  16600. if (this._mustWipeVertexAttributes) {
  16601. this._mustWipeVertexAttributes = false;
  16602. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16603. this._gl.disableVertexAttribArray(i);
  16604. this._vertexAttribArraysEnabled[i] = false;
  16605. this._currentBufferPointers[i].active = false;
  16606. }
  16607. return;
  16608. }
  16609. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16610. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16611. continue;
  16612. }
  16613. this._gl.disableVertexAttribArray(i);
  16614. this._vertexAttribArraysEnabled[i] = false;
  16615. this._currentBufferPointers[i].active = false;
  16616. }
  16617. };
  16618. /**
  16619. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16620. */
  16621. Engine.prototype.releaseEffects = function () {
  16622. for (var name in this._compiledEffects) {
  16623. this._deleteProgram(this._compiledEffects[name]._program);
  16624. }
  16625. this._compiledEffects = {};
  16626. };
  16627. /**
  16628. * Dispose and release all associated resources
  16629. */
  16630. Engine.prototype.dispose = function () {
  16631. this.hideLoadingUI();
  16632. this.stopRenderLoop();
  16633. // Release postProcesses
  16634. while (this.postProcesses.length) {
  16635. this.postProcesses[0].dispose();
  16636. }
  16637. // Empty texture
  16638. if (this._emptyTexture) {
  16639. this._releaseTexture(this._emptyTexture);
  16640. this._emptyTexture = null;
  16641. }
  16642. if (this._emptyCubeTexture) {
  16643. this._releaseTexture(this._emptyCubeTexture);
  16644. this._emptyCubeTexture = null;
  16645. }
  16646. // Rescale PP
  16647. if (this._rescalePostProcess) {
  16648. this._rescalePostProcess.dispose();
  16649. }
  16650. // Release scenes
  16651. while (this.scenes.length) {
  16652. this.scenes[0].dispose();
  16653. }
  16654. // Release audio engine
  16655. if (Engine.audioEngine) {
  16656. Engine.audioEngine.dispose();
  16657. }
  16658. // Release effects
  16659. this.releaseEffects();
  16660. // Unbind
  16661. this.unbindAllAttributes();
  16662. this._boundUniforms = [];
  16663. if (this._dummyFramebuffer) {
  16664. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16665. }
  16666. //WebVR
  16667. this.disableVR();
  16668. // Events
  16669. if (BABYLON.Tools.IsWindowObjectExist()) {
  16670. window.removeEventListener("blur", this._onBlur);
  16671. window.removeEventListener("focus", this._onFocus);
  16672. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16673. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16674. if (this._renderingCanvas) {
  16675. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16676. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16677. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16678. if (!this._doNotHandleContextLost) {
  16679. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16680. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16681. }
  16682. }
  16683. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16684. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16685. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16686. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16687. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16688. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16689. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16690. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16691. if (this._onVrDisplayConnect) {
  16692. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16693. if (this._onVrDisplayDisconnect) {
  16694. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16695. }
  16696. if (this._onVrDisplayPresentChange) {
  16697. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16698. }
  16699. this._onVrDisplayConnect = null;
  16700. this._onVrDisplayDisconnect = null;
  16701. }
  16702. }
  16703. // Remove from Instances
  16704. var index = Engine.Instances.indexOf(this);
  16705. if (index >= 0) {
  16706. Engine.Instances.splice(index, 1);
  16707. }
  16708. this._workingCanvas = null;
  16709. this._workingContext = null;
  16710. this._currentBufferPointers = [];
  16711. this._renderingCanvas = null;
  16712. this._currentProgram = null;
  16713. this._bindedRenderFunction = null;
  16714. this.onResizeObservable.clear();
  16715. this.onCanvasBlurObservable.clear();
  16716. this.onCanvasFocusObservable.clear();
  16717. this.onCanvasPointerOutObservable.clear();
  16718. this.onBeginFrameObservable.clear();
  16719. this.onEndFrameObservable.clear();
  16720. BABYLON.Effect.ResetCache();
  16721. // Abort active requests
  16722. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16723. var request = _a[_i];
  16724. request.abort();
  16725. }
  16726. };
  16727. // Loading screen
  16728. /**
  16729. * Display the loading screen
  16730. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16731. */
  16732. Engine.prototype.displayLoadingUI = function () {
  16733. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16734. return;
  16735. }
  16736. var loadingScreen = this.loadingScreen;
  16737. if (loadingScreen) {
  16738. loadingScreen.displayLoadingUI();
  16739. }
  16740. };
  16741. /**
  16742. * Hide the loading screen
  16743. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16744. */
  16745. Engine.prototype.hideLoadingUI = function () {
  16746. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16747. return;
  16748. }
  16749. var loadingScreen = this.loadingScreen;
  16750. if (loadingScreen) {
  16751. loadingScreen.hideLoadingUI();
  16752. }
  16753. };
  16754. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16755. /**
  16756. * Gets the current loading screen object
  16757. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16758. */
  16759. get: function () {
  16760. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16761. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16762. return this._loadingScreen;
  16763. },
  16764. /**
  16765. * Sets the current loading screen object
  16766. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16767. */
  16768. set: function (loadingScreen) {
  16769. this._loadingScreen = loadingScreen;
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16775. /**
  16776. * Sets the current loading screen text
  16777. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16778. */
  16779. set: function (text) {
  16780. this.loadingScreen.loadingUIText = text;
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16786. /**
  16787. * Sets the current loading screen background color
  16788. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16789. */
  16790. set: function (color) {
  16791. this.loadingScreen.loadingUIBackgroundColor = color;
  16792. },
  16793. enumerable: true,
  16794. configurable: true
  16795. });
  16796. /**
  16797. * Attach a new callback raised when context lost event is fired
  16798. * @param callback defines the callback to call
  16799. */
  16800. Engine.prototype.attachContextLostEvent = function (callback) {
  16801. if (this._renderingCanvas) {
  16802. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16803. }
  16804. };
  16805. /**
  16806. * Attach a new callback raised when context restored event is fired
  16807. * @param callback defines the callback to call
  16808. */
  16809. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16810. if (this._renderingCanvas) {
  16811. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16812. }
  16813. };
  16814. /**
  16815. * Gets the source code of the vertex shader associated with a specific webGL program
  16816. * @param program defines the program to use
  16817. * @returns a string containing the source code of the vertex shader associated with the program
  16818. */
  16819. Engine.prototype.getVertexShaderSource = function (program) {
  16820. var shaders = this._gl.getAttachedShaders(program);
  16821. if (!shaders) {
  16822. return null;
  16823. }
  16824. return this._gl.getShaderSource(shaders[0]);
  16825. };
  16826. /**
  16827. * Gets the source code of the fragment shader associated with a specific webGL program
  16828. * @param program defines the program to use
  16829. * @returns a string containing the source code of the fragment shader associated with the program
  16830. */
  16831. Engine.prototype.getFragmentShaderSource = function (program) {
  16832. var shaders = this._gl.getAttachedShaders(program);
  16833. if (!shaders) {
  16834. return null;
  16835. }
  16836. return this._gl.getShaderSource(shaders[1]);
  16837. };
  16838. /**
  16839. * Get the current error code of the webGL context
  16840. * @returns the error code
  16841. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16842. */
  16843. Engine.prototype.getError = function () {
  16844. return this._gl.getError();
  16845. };
  16846. // FPS
  16847. /**
  16848. * Gets the current framerate
  16849. * @returns a number representing the framerate
  16850. */
  16851. Engine.prototype.getFps = function () {
  16852. return this._fps;
  16853. };
  16854. /**
  16855. * Gets the time spent between current and previous frame
  16856. * @returns a number representing the delta time in ms
  16857. */
  16858. Engine.prototype.getDeltaTime = function () {
  16859. return this._deltaTime;
  16860. };
  16861. Engine.prototype._measureFps = function () {
  16862. this._performanceMonitor.sampleFrame();
  16863. this._fps = this._performanceMonitor.averageFPS;
  16864. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16865. };
  16866. /** @hidden */
  16867. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16868. if (faceIndex === void 0) { faceIndex = -1; }
  16869. if (level === void 0) { level = 0; }
  16870. var gl = this._gl;
  16871. if (!this._dummyFramebuffer) {
  16872. var dummy = gl.createFramebuffer();
  16873. if (!dummy) {
  16874. throw new Error("Unable to create dummy framebuffer");
  16875. }
  16876. this._dummyFramebuffer = dummy;
  16877. }
  16878. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16879. if (faceIndex > -1) {
  16880. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16881. }
  16882. else {
  16883. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16884. }
  16885. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16886. var buffer;
  16887. switch (readType) {
  16888. case gl.UNSIGNED_BYTE:
  16889. buffer = new Uint8Array(4 * width * height);
  16890. readType = gl.UNSIGNED_BYTE;
  16891. break;
  16892. default:
  16893. buffer = new Float32Array(4 * width * height);
  16894. readType = gl.FLOAT;
  16895. break;
  16896. }
  16897. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16898. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16899. return buffer;
  16900. };
  16901. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16902. if (this._webGLVersion > 1) {
  16903. return this._caps.colorBufferFloat;
  16904. }
  16905. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16906. };
  16907. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16908. if (this._webGLVersion > 1) {
  16909. return this._caps.colorBufferFloat;
  16910. }
  16911. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16912. };
  16913. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16914. Engine.prototype._canRenderToFramebuffer = function (type) {
  16915. var gl = this._gl;
  16916. //clear existing errors
  16917. while (gl.getError() !== gl.NO_ERROR) { }
  16918. var successful = true;
  16919. var texture = gl.createTexture();
  16920. gl.bindTexture(gl.TEXTURE_2D, texture);
  16921. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16922. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16923. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16924. var fb = gl.createFramebuffer();
  16925. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16926. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16927. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16928. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16929. successful = successful && (gl.getError() === gl.NO_ERROR);
  16930. //try render by clearing frame buffer's color buffer
  16931. if (successful) {
  16932. gl.clear(gl.COLOR_BUFFER_BIT);
  16933. successful = successful && (gl.getError() === gl.NO_ERROR);
  16934. }
  16935. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16936. if (successful) {
  16937. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16938. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16939. var readFormat = gl.RGBA;
  16940. var readType = gl.UNSIGNED_BYTE;
  16941. var buffer = new Uint8Array(4);
  16942. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16943. successful = successful && (gl.getError() === gl.NO_ERROR);
  16944. }
  16945. //clean up
  16946. gl.deleteTexture(texture);
  16947. gl.deleteFramebuffer(fb);
  16948. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16949. //clear accumulated errors
  16950. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16951. return successful;
  16952. };
  16953. /** @hidden */
  16954. Engine.prototype._getWebGLTextureType = function (type) {
  16955. if (this._webGLVersion === 1) {
  16956. switch (type) {
  16957. case Engine.TEXTURETYPE_FLOAT:
  16958. return this._gl.FLOAT;
  16959. case Engine.TEXTURETYPE_HALF_FLOAT:
  16960. return this._gl.HALF_FLOAT_OES;
  16961. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16962. return this._gl.UNSIGNED_BYTE;
  16963. }
  16964. return this._gl.UNSIGNED_BYTE;
  16965. }
  16966. switch (type) {
  16967. case Engine.TEXTURETYPE_BYTE:
  16968. return this._gl.BYTE;
  16969. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16970. return this._gl.UNSIGNED_BYTE;
  16971. case Engine.TEXTURETYPE_SHORT:
  16972. return this._gl.SHORT;
  16973. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16974. return this._gl.UNSIGNED_SHORT;
  16975. case Engine.TEXTURETYPE_INT:
  16976. return this._gl.INT;
  16977. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16978. return this._gl.UNSIGNED_INT;
  16979. case Engine.TEXTURETYPE_FLOAT:
  16980. return this._gl.FLOAT;
  16981. case Engine.TEXTURETYPE_HALF_FLOAT:
  16982. return this._gl.HALF_FLOAT;
  16983. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16984. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16985. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16986. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16987. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16988. return this._gl.UNSIGNED_SHORT_5_6_5;
  16989. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16990. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16991. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16992. return this._gl.UNSIGNED_INT_24_8;
  16993. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16994. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16995. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16996. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16997. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16998. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16999. }
  17000. return this._gl.UNSIGNED_BYTE;
  17001. };
  17002. ;
  17003. Engine.prototype._getInternalFormat = function (format) {
  17004. var internalFormat = this._gl.RGBA;
  17005. switch (format) {
  17006. case Engine.TEXTUREFORMAT_ALPHA:
  17007. internalFormat = this._gl.ALPHA;
  17008. break;
  17009. case Engine.TEXTUREFORMAT_LUMINANCE:
  17010. internalFormat = this._gl.LUMINANCE;
  17011. break;
  17012. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17013. internalFormat = this._gl.LUMINANCE_ALPHA;
  17014. break;
  17015. case Engine.TEXTUREFORMAT_RED:
  17016. internalFormat = this._gl.RED;
  17017. break;
  17018. case Engine.TEXTUREFORMAT_RG:
  17019. internalFormat = this._gl.RG;
  17020. break;
  17021. case Engine.TEXTUREFORMAT_RGB:
  17022. internalFormat = this._gl.RGB;
  17023. break;
  17024. case Engine.TEXTUREFORMAT_RGBA:
  17025. internalFormat = this._gl.RGBA;
  17026. break;
  17027. }
  17028. if (this._webGLVersion > 1) {
  17029. switch (format) {
  17030. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17031. internalFormat = this._gl.RED_INTEGER;
  17032. break;
  17033. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17034. internalFormat = this._gl.RG_INTEGER;
  17035. break;
  17036. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17037. internalFormat = this._gl.RGB_INTEGER;
  17038. break;
  17039. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17040. internalFormat = this._gl.RGBA_INTEGER;
  17041. break;
  17042. }
  17043. }
  17044. return internalFormat;
  17045. };
  17046. /** @hidden */
  17047. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17048. if (this._webGLVersion === 1) {
  17049. if (format !== undefined) {
  17050. switch (format) {
  17051. case Engine.TEXTUREFORMAT_ALPHA:
  17052. return this._gl.ALPHA;
  17053. case Engine.TEXTUREFORMAT_LUMINANCE:
  17054. return this._gl.LUMINANCE;
  17055. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17056. return this._gl.LUMINANCE_ALPHA;
  17057. }
  17058. }
  17059. return this._gl.RGBA;
  17060. }
  17061. switch (type) {
  17062. case Engine.TEXTURETYPE_BYTE:
  17063. switch (format) {
  17064. case Engine.TEXTUREFORMAT_RED:
  17065. return this._gl.R8_SNORM;
  17066. case Engine.TEXTUREFORMAT_RG:
  17067. return this._gl.RG8_SNORM;
  17068. case Engine.TEXTUREFORMAT_RGB:
  17069. return this._gl.RGB8_SNORM;
  17070. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17071. return this._gl.R8I;
  17072. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17073. return this._gl.RG8I;
  17074. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17075. return this._gl.RGB8I;
  17076. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17077. return this._gl.RGBA8I;
  17078. default:
  17079. return this._gl.RGBA8_SNORM;
  17080. }
  17081. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17082. switch (format) {
  17083. case Engine.TEXTUREFORMAT_RED:
  17084. return this._gl.R8;
  17085. case Engine.TEXTUREFORMAT_RG:
  17086. return this._gl.RG8;
  17087. case Engine.TEXTUREFORMAT_RGB:
  17088. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17089. case Engine.TEXTUREFORMAT_RGBA:
  17090. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17091. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17092. return this._gl.R8UI;
  17093. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17094. return this._gl.RG8UI;
  17095. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17096. return this._gl.RGB8UI;
  17097. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17098. return this._gl.RGBA8UI;
  17099. default:
  17100. return this._gl.RGBA8;
  17101. }
  17102. case Engine.TEXTURETYPE_SHORT:
  17103. switch (format) {
  17104. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17105. return this._gl.R16I;
  17106. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17107. return this._gl.RG16I;
  17108. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17109. return this._gl.RGB16I;
  17110. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17111. return this._gl.RGBA16I;
  17112. default:
  17113. return this._gl.RGBA16I;
  17114. }
  17115. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17116. switch (format) {
  17117. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17118. return this._gl.R16UI;
  17119. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17120. return this._gl.RG16UI;
  17121. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17122. return this._gl.RGB16UI;
  17123. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17124. return this._gl.RGBA16UI;
  17125. default:
  17126. return this._gl.RGBA16UI;
  17127. }
  17128. case Engine.TEXTURETYPE_INT:
  17129. switch (format) {
  17130. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17131. return this._gl.R32I;
  17132. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17133. return this._gl.RG32I;
  17134. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17135. return this._gl.RGB32I;
  17136. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17137. return this._gl.RGBA32I;
  17138. default:
  17139. return this._gl.RGBA32I;
  17140. }
  17141. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17142. switch (format) {
  17143. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17144. return this._gl.R32UI;
  17145. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17146. return this._gl.RG32UI;
  17147. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17148. return this._gl.RGB32UI;
  17149. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17150. return this._gl.RGBA32UI;
  17151. default:
  17152. return this._gl.RGBA32UI;
  17153. }
  17154. case Engine.TEXTURETYPE_FLOAT:
  17155. switch (format) {
  17156. case Engine.TEXTUREFORMAT_RED:
  17157. return this._gl.R32F; // By default. Other possibility is R16F.
  17158. case Engine.TEXTUREFORMAT_RG:
  17159. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17160. case Engine.TEXTUREFORMAT_RGB:
  17161. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17162. case Engine.TEXTUREFORMAT_RGBA:
  17163. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17164. default:
  17165. return this._gl.RGBA32F;
  17166. }
  17167. case Engine.TEXTURETYPE_HALF_FLOAT:
  17168. switch (format) {
  17169. case Engine.TEXTUREFORMAT_RED:
  17170. return this._gl.R16F;
  17171. case Engine.TEXTUREFORMAT_RG:
  17172. return this._gl.RG16F;
  17173. case Engine.TEXTUREFORMAT_RGB:
  17174. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17175. case Engine.TEXTUREFORMAT_RGBA:
  17176. return this._gl.RGBA16F;
  17177. default:
  17178. return this._gl.RGBA16F;
  17179. }
  17180. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17181. return this._gl.RGB565;
  17182. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17183. return this._gl.R11F_G11F_B10F;
  17184. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17185. return this._gl.RGB9_E5;
  17186. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17187. return this._gl.RGBA4;
  17188. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17189. return this._gl.RGB5_A1;
  17190. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17191. switch (format) {
  17192. case Engine.TEXTUREFORMAT_RGBA:
  17193. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17194. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17195. return this._gl.RGB10_A2UI;
  17196. default:
  17197. return this._gl.RGB10_A2;
  17198. }
  17199. }
  17200. return this._gl.RGBA8;
  17201. };
  17202. ;
  17203. /** @hidden */
  17204. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17205. if (type === Engine.TEXTURETYPE_FLOAT) {
  17206. return this._gl.RGBA32F;
  17207. }
  17208. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17209. return this._gl.RGBA16F;
  17210. }
  17211. return this._gl.RGBA8;
  17212. };
  17213. ;
  17214. /** @hidden */
  17215. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17216. var _this = this;
  17217. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17218. this._activeRequests.push(request);
  17219. request.onCompleteObservable.add(function (request) {
  17220. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17221. });
  17222. return request;
  17223. };
  17224. /** @hidden */
  17225. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17226. var _this = this;
  17227. return new Promise(function (resolve, reject) {
  17228. _this._loadFile(url, function (data) {
  17229. resolve(data);
  17230. }, undefined, database, useArrayBuffer, function (request, exception) {
  17231. reject(exception);
  17232. });
  17233. });
  17234. };
  17235. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17236. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17237. var onload = function (data) {
  17238. loadedFiles[index] = data;
  17239. loadedFiles._internalCount++;
  17240. if (loadedFiles._internalCount === 6) {
  17241. onfinish(loadedFiles);
  17242. }
  17243. };
  17244. var onerror = function (request, exception) {
  17245. if (onErrorCallBack && request) {
  17246. onErrorCallBack(request.status + " " + request.statusText, exception);
  17247. }
  17248. };
  17249. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17250. };
  17251. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17252. if (onError === void 0) { onError = null; }
  17253. var loadedFiles = [];
  17254. loadedFiles._internalCount = 0;
  17255. for (var index = 0; index < 6; index++) {
  17256. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17257. }
  17258. };
  17259. // Statics
  17260. /**
  17261. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17262. * @returns true if the engine can be created
  17263. * @ignorenaming
  17264. */
  17265. Engine.isSupported = function () {
  17266. try {
  17267. var tempcanvas = document.createElement("canvas");
  17268. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17269. return gl != null && !!window.WebGLRenderingContext;
  17270. }
  17271. catch (e) {
  17272. return false;
  17273. }
  17274. };
  17275. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17276. Engine.ExceptionList = [
  17277. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17278. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17279. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17280. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17281. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17282. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17283. ];
  17284. /** Gets the list of created engines */
  17285. Engine.Instances = new Array();
  17286. /**
  17287. * Hidden
  17288. */
  17289. Engine._TextureLoaders = [];
  17290. // Const statics
  17291. /** Defines that alpha blending is disabled */
  17292. Engine.ALPHA_DISABLE = 0;
  17293. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17294. Engine.ALPHA_ADD = 1;
  17295. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17296. Engine.ALPHA_COMBINE = 2;
  17297. /** Defines that alpha blending to DEST - SRC * DEST */
  17298. Engine.ALPHA_SUBTRACT = 3;
  17299. /** Defines that alpha blending to SRC * DEST */
  17300. Engine.ALPHA_MULTIPLY = 4;
  17301. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17302. Engine.ALPHA_MAXIMIZED = 5;
  17303. /** Defines that alpha blending to SRC + DEST */
  17304. Engine.ALPHA_ONEONE = 6;
  17305. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17306. Engine.ALPHA_PREMULTIPLIED = 7;
  17307. /**
  17308. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17309. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17310. */
  17311. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17312. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17313. Engine.ALPHA_INTERPOLATE = 9;
  17314. /**
  17315. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17316. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17317. */
  17318. Engine.ALPHA_SCREENMODE = 10;
  17319. /** Defines that the ressource is not delayed*/
  17320. Engine.DELAYLOADSTATE_NONE = 0;
  17321. /** Defines that the ressource was successfully delay loaded */
  17322. Engine.DELAYLOADSTATE_LOADED = 1;
  17323. /** Defines that the ressource is currently delay loading */
  17324. Engine.DELAYLOADSTATE_LOADING = 2;
  17325. /** Defines that the ressource is delayed and has not started loading */
  17326. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17327. // Depht or Stencil test Constants.
  17328. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17329. Engine.NEVER = 0x0200;
  17330. /** 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 */
  17331. Engine.ALWAYS = 0x0207;
  17332. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17333. Engine.LESS = 0x0201;
  17334. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17335. Engine.EQUAL = 0x0202;
  17336. /** 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 */
  17337. Engine.LEQUAL = 0x0203;
  17338. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17339. Engine.GREATER = 0x0204;
  17340. /** 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 */
  17341. Engine.GEQUAL = 0x0206;
  17342. /** 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 */
  17343. Engine.NOTEQUAL = 0x0205;
  17344. // Stencil Actions Constants.
  17345. /** Passed to stencilOperation to specify that stencil value must be kept */
  17346. Engine.KEEP = 0x1E00;
  17347. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17348. Engine.REPLACE = 0x1E01;
  17349. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17350. Engine.INCR = 0x1E02;
  17351. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17352. Engine.DECR = 0x1E03;
  17353. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17354. Engine.INVERT = 0x150A;
  17355. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17356. Engine.INCR_WRAP = 0x8507;
  17357. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17358. Engine.DECR_WRAP = 0x8508;
  17359. /** Texture is not repeating outside of 0..1 UVs */
  17360. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17361. /** Texture is repeating outside of 0..1 UVs */
  17362. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17363. /** Texture is repeating and mirrored */
  17364. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17365. /** ALPHA */
  17366. Engine.TEXTUREFORMAT_ALPHA = 0;
  17367. /** LUMINANCE */
  17368. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17369. /** LUMINANCE_ALPHA */
  17370. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17371. /** RGB */
  17372. Engine.TEXTUREFORMAT_RGB = 4;
  17373. /** RGBA */
  17374. Engine.TEXTUREFORMAT_RGBA = 5;
  17375. /** RED */
  17376. Engine.TEXTUREFORMAT_RED = 6;
  17377. /** RED (2nd reference) */
  17378. Engine.TEXTUREFORMAT_R = 6;
  17379. /** RG */
  17380. Engine.TEXTUREFORMAT_RG = 7;
  17381. /** RED_INTEGER */
  17382. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17383. /** RED_INTEGER (2nd reference) */
  17384. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17385. /** RG_INTEGER */
  17386. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17387. /** RGB_INTEGER */
  17388. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17389. /** RGBA_INTEGER */
  17390. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17391. /** UNSIGNED_BYTE */
  17392. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17393. /** UNSIGNED_BYTE (2nd reference) */
  17394. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17395. /** FLOAT */
  17396. Engine.TEXTURETYPE_FLOAT = 1;
  17397. /** HALF_FLOAT */
  17398. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17399. /** BYTE */
  17400. Engine.TEXTURETYPE_BYTE = 3;
  17401. /** SHORT */
  17402. Engine.TEXTURETYPE_SHORT = 4;
  17403. /** UNSIGNED_SHORT */
  17404. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17405. /** INT */
  17406. Engine.TEXTURETYPE_INT = 6;
  17407. /** UNSIGNED_INT */
  17408. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17409. /** UNSIGNED_SHORT_4_4_4_4 */
  17410. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17411. /** UNSIGNED_SHORT_5_5_5_1 */
  17412. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17413. /** UNSIGNED_SHORT_5_6_5 */
  17414. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17415. /** UNSIGNED_INT_2_10_10_10_REV */
  17416. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17417. /** UNSIGNED_INT_24_8 */
  17418. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17419. /** UNSIGNED_INT_10F_11F_11F_REV */
  17420. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17421. /** UNSIGNED_INT_5_9_9_9_REV */
  17422. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17423. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17424. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17425. /** nearest is mag = nearest and min = nearest and mip = linear */
  17426. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17427. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17428. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17429. /** Trilinear is mag = linear and min = linear and mip = linear */
  17430. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17431. /** nearest is mag = nearest and min = nearest and mip = linear */
  17432. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17433. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17434. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17435. /** Trilinear is mag = linear and min = linear and mip = linear */
  17436. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17437. /** mag = nearest and min = nearest and mip = nearest */
  17438. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17439. /** mag = nearest and min = linear and mip = nearest */
  17440. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17441. /** mag = nearest and min = linear and mip = linear */
  17442. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17443. /** mag = nearest and min = linear and mip = none */
  17444. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17445. /** mag = nearest and min = nearest and mip = none */
  17446. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17447. /** mag = linear and min = nearest and mip = nearest */
  17448. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17449. /** mag = linear and min = nearest and mip = linear */
  17450. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17451. /** mag = linear and min = linear and mip = none */
  17452. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17453. /** mag = linear and min = nearest and mip = none */
  17454. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17455. /** Explicit coordinates mode */
  17456. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17457. /** Spherical coordinates mode */
  17458. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17459. /** Planar coordinates mode */
  17460. Engine.TEXTURE_PLANAR_MODE = 2;
  17461. /** Cubic coordinates mode */
  17462. Engine.TEXTURE_CUBIC_MODE = 3;
  17463. /** Projection coordinates mode */
  17464. Engine.TEXTURE_PROJECTION_MODE = 4;
  17465. /** Skybox coordinates mode */
  17466. Engine.TEXTURE_SKYBOX_MODE = 5;
  17467. /** Inverse Cubic coordinates mode */
  17468. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17469. /** Equirectangular coordinates mode */
  17470. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17471. /** Equirectangular Fixed coordinates mode */
  17472. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17473. /** Equirectangular Fixed Mirrored coordinates mode */
  17474. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17475. // Texture rescaling mode
  17476. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17477. Engine.SCALEMODE_FLOOR = 1;
  17478. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17479. Engine.SCALEMODE_NEAREST = 2;
  17480. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17481. Engine.SCALEMODE_CEILING = 3;
  17482. // Updatable statics so stick with vars here
  17483. /**
  17484. * Gets or sets the epsilon value used by collision engine
  17485. */
  17486. Engine.CollisionsEpsilon = 0.001;
  17487. /**
  17488. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17489. */
  17490. Engine.CodeRepository = "src/";
  17491. /**
  17492. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17493. */
  17494. Engine.ShadersRepository = "src/Shaders/";
  17495. return Engine;
  17496. }());
  17497. BABYLON.Engine = Engine;
  17498. })(BABYLON || (BABYLON = {}));
  17499. //# sourceMappingURL=babylon.engine.js.map
  17500. var BABYLON;
  17501. (function (BABYLON) {
  17502. /**
  17503. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17504. */
  17505. var Node = /** @class */ (function () {
  17506. /**
  17507. * Creates a new Node
  17508. * @param {string} name - the name and id to be given to this node
  17509. * @param {BABYLON.Scene} the scene this node will be added to
  17510. */
  17511. function Node(name, scene) {
  17512. if (scene === void 0) { scene = null; }
  17513. /**
  17514. * Gets or sets a string used to store user defined state for the node
  17515. */
  17516. this.state = "";
  17517. /**
  17518. * Gets or sets an object used to store user defined information for the node
  17519. */
  17520. this.metadata = null;
  17521. /**
  17522. * Gets or sets a boolean used to define if the node must be serialized
  17523. */
  17524. this.doNotSerialize = false;
  17525. /** @hidden */
  17526. this._isDisposed = false;
  17527. /**
  17528. * Gets a list of Animations associated with the node
  17529. */
  17530. this.animations = new Array();
  17531. this._ranges = {};
  17532. this._isEnabled = true;
  17533. this._isReady = true;
  17534. /** @hidden */
  17535. this._currentRenderId = -1;
  17536. this._parentRenderId = -1;
  17537. this._childRenderId = -1;
  17538. this._animationPropertiesOverride = null;
  17539. /**
  17540. * An event triggered when the mesh is disposed
  17541. */
  17542. this.onDisposeObservable = new BABYLON.Observable();
  17543. // Behaviors
  17544. this._behaviors = new Array();
  17545. this.name = name;
  17546. this.id = name;
  17547. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17548. this.uniqueId = this._scene.getUniqueId();
  17549. this._initCache();
  17550. }
  17551. /**
  17552. * Add a new node constructor
  17553. * @param type defines the type name of the node to construct
  17554. * @param constructorFunc defines the constructor function
  17555. */
  17556. Node.AddNodeConstructor = function (type, constructorFunc) {
  17557. this._NodeConstructors[type] = constructorFunc;
  17558. };
  17559. /**
  17560. * Returns a node constructor based on type name
  17561. * @param type defines the type name
  17562. * @param name defines the new node name
  17563. * @param scene defines the hosting scene
  17564. * @param options defines optional options to transmit to constructors
  17565. * @returns the new constructor or null
  17566. */
  17567. Node.Construct = function (type, name, scene, options) {
  17568. var constructorFunc = this._NodeConstructors[type];
  17569. if (!constructorFunc) {
  17570. return null;
  17571. }
  17572. return constructorFunc(name, scene, options);
  17573. };
  17574. /**
  17575. * Gets a boolean indicating if the node has been disposed
  17576. * @returns true if the node was disposed
  17577. */
  17578. Node.prototype.isDisposed = function () {
  17579. return this._isDisposed;
  17580. };
  17581. Object.defineProperty(Node.prototype, "parent", {
  17582. get: function () {
  17583. return this._parentNode;
  17584. },
  17585. /**
  17586. * Gets or sets the parent of the node
  17587. */
  17588. set: function (parent) {
  17589. if (this._parentNode === parent) {
  17590. return;
  17591. }
  17592. // Remove self from list of children of parent
  17593. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17594. var index = this._parentNode._children.indexOf(this);
  17595. if (index !== -1) {
  17596. this._parentNode._children.splice(index, 1);
  17597. }
  17598. }
  17599. // Store new parent
  17600. this._parentNode = parent;
  17601. // Add as child to new parent
  17602. if (this._parentNode) {
  17603. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17604. this._parentNode._children = new Array();
  17605. }
  17606. this._parentNode._children.push(this);
  17607. }
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17613. /**
  17614. * Gets or sets the animation properties override
  17615. */
  17616. get: function () {
  17617. if (!this._animationPropertiesOverride) {
  17618. return this._scene.animationPropertiesOverride;
  17619. }
  17620. return this._animationPropertiesOverride;
  17621. },
  17622. set: function (value) {
  17623. this._animationPropertiesOverride = value;
  17624. },
  17625. enumerable: true,
  17626. configurable: true
  17627. });
  17628. /**
  17629. * Gets a string idenfifying the name of the class
  17630. * @returns "Node" string
  17631. */
  17632. Node.prototype.getClassName = function () {
  17633. return "Node";
  17634. };
  17635. Object.defineProperty(Node.prototype, "onDispose", {
  17636. /**
  17637. * Sets a callback that will be raised when the node will be disposed
  17638. */
  17639. set: function (callback) {
  17640. if (this._onDisposeObserver) {
  17641. this.onDisposeObservable.remove(this._onDisposeObserver);
  17642. }
  17643. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. /**
  17649. * Gets the scene of the node
  17650. * @returns a {BABYLON.Scene}
  17651. */
  17652. Node.prototype.getScene = function () {
  17653. return this._scene;
  17654. };
  17655. /**
  17656. * Gets the engine of the node
  17657. * @returns a {BABYLON.Engine}
  17658. */
  17659. Node.prototype.getEngine = function () {
  17660. return this._scene.getEngine();
  17661. };
  17662. /**
  17663. * Attach a behavior to the node
  17664. * @see http://doc.babylonjs.com/features/behaviour
  17665. * @param behavior defines the behavior to attach
  17666. * @returns the current Node
  17667. */
  17668. Node.prototype.addBehavior = function (behavior) {
  17669. var _this = this;
  17670. var index = this._behaviors.indexOf(behavior);
  17671. if (index !== -1) {
  17672. return this;
  17673. }
  17674. behavior.init();
  17675. if (this._scene.isLoading) {
  17676. // We defer the attach when the scene will be loaded
  17677. this._scene.onDataLoadedObservable.addOnce(function () {
  17678. behavior.attach(_this);
  17679. });
  17680. }
  17681. else {
  17682. behavior.attach(this);
  17683. }
  17684. this._behaviors.push(behavior);
  17685. return this;
  17686. };
  17687. /**
  17688. * Remove an attached behavior
  17689. * @see http://doc.babylonjs.com/features/behaviour
  17690. * @param behavior defines the behavior to attach
  17691. * @returns the current Node
  17692. */
  17693. Node.prototype.removeBehavior = function (behavior) {
  17694. var index = this._behaviors.indexOf(behavior);
  17695. if (index === -1) {
  17696. return this;
  17697. }
  17698. this._behaviors[index].detach();
  17699. this._behaviors.splice(index, 1);
  17700. return this;
  17701. };
  17702. Object.defineProperty(Node.prototype, "behaviors", {
  17703. /**
  17704. * Gets the list of attached behaviors
  17705. * @see http://doc.babylonjs.com/features/behaviour
  17706. */
  17707. get: function () {
  17708. return this._behaviors;
  17709. },
  17710. enumerable: true,
  17711. configurable: true
  17712. });
  17713. /**
  17714. * Gets an attached behavior by name
  17715. * @param name defines the name of the behavior to look for
  17716. * @see http://doc.babylonjs.com/features/behaviour
  17717. * @returns null if behavior was not found else the requested behavior
  17718. */
  17719. Node.prototype.getBehaviorByName = function (name) {
  17720. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17721. var behavior = _a[_i];
  17722. if (behavior.name === name) {
  17723. return behavior;
  17724. }
  17725. }
  17726. return null;
  17727. };
  17728. /**
  17729. * Returns the world matrix of the node
  17730. * @returns a matrix containing the node's world matrix
  17731. */
  17732. Node.prototype.getWorldMatrix = function () {
  17733. return BABYLON.Matrix.Identity();
  17734. };
  17735. /** @hidden */
  17736. Node.prototype._getWorldMatrixDeterminant = function () {
  17737. return 1;
  17738. };
  17739. // override it in derived class if you add new variables to the cache
  17740. // and call the parent class method
  17741. /** @hidden */
  17742. Node.prototype._initCache = function () {
  17743. this._cache = {};
  17744. this._cache.parent = undefined;
  17745. };
  17746. /** @hidden */
  17747. Node.prototype.updateCache = function (force) {
  17748. if (!force && this.isSynchronized())
  17749. return;
  17750. this._cache.parent = this.parent;
  17751. this._updateCache();
  17752. };
  17753. // override it in derived class if you add new variables to the cache
  17754. // and call the parent class method if !ignoreParentClass
  17755. /** @hidden */
  17756. Node.prototype._updateCache = function (ignoreParentClass) {
  17757. };
  17758. // override it in derived class if you add new variables to the cache
  17759. /** @hidden */
  17760. Node.prototype._isSynchronized = function () {
  17761. return true;
  17762. };
  17763. /** @hidden */
  17764. Node.prototype._markSyncedWithParent = function () {
  17765. if (this.parent) {
  17766. this._parentRenderId = this.parent._childRenderId;
  17767. }
  17768. };
  17769. /** @hidden */
  17770. Node.prototype.isSynchronizedWithParent = function () {
  17771. if (!this.parent) {
  17772. return true;
  17773. }
  17774. if (this._parentRenderId !== this.parent._childRenderId) {
  17775. return false;
  17776. }
  17777. return this.parent.isSynchronized();
  17778. };
  17779. /** @hidden */
  17780. Node.prototype.isSynchronized = function (updateCache) {
  17781. var check = this.hasNewParent();
  17782. check = check || !this.isSynchronizedWithParent();
  17783. check = check || !this._isSynchronized();
  17784. if (updateCache)
  17785. this.updateCache(true);
  17786. return !check;
  17787. };
  17788. /** @hidden */
  17789. Node.prototype.hasNewParent = function () {
  17790. if (this._cache.parent === this.parent)
  17791. return false;
  17792. this._cache.parent = this.parent;
  17793. return true;
  17794. };
  17795. /**
  17796. * Is this node ready to be used/rendered
  17797. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17798. * @return true if the node is ready
  17799. */
  17800. Node.prototype.isReady = function (completeCheck) {
  17801. if (completeCheck === void 0) { completeCheck = false; }
  17802. return this._isReady;
  17803. };
  17804. /**
  17805. * Is this node enabled?
  17806. * 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
  17807. * @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
  17808. * @return whether this node (and its parent) is enabled
  17809. */
  17810. Node.prototype.isEnabled = function (checkAncestors) {
  17811. if (checkAncestors === void 0) { checkAncestors = true; }
  17812. if (checkAncestors === false) {
  17813. return this._isEnabled;
  17814. }
  17815. if (this._isEnabled === false) {
  17816. return false;
  17817. }
  17818. if (this.parent !== undefined && this.parent !== null) {
  17819. return this.parent.isEnabled(checkAncestors);
  17820. }
  17821. return true;
  17822. };
  17823. /**
  17824. * Set the enabled state of this node
  17825. * @param value defines the new enabled state
  17826. */
  17827. Node.prototype.setEnabled = function (value) {
  17828. this._isEnabled = value;
  17829. };
  17830. /**
  17831. * Is this node a descendant of the given node?
  17832. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17833. * @param ancestor defines the parent node to inspect
  17834. * @returns a boolean indicating if this node is a descendant of the given node
  17835. */
  17836. Node.prototype.isDescendantOf = function (ancestor) {
  17837. if (this.parent) {
  17838. if (this.parent === ancestor) {
  17839. return true;
  17840. }
  17841. return this.parent.isDescendantOf(ancestor);
  17842. }
  17843. return false;
  17844. };
  17845. /** @hidden */
  17846. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17847. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17848. if (!this._children) {
  17849. return;
  17850. }
  17851. for (var index = 0; index < this._children.length; index++) {
  17852. var item = this._children[index];
  17853. if (!predicate || predicate(item)) {
  17854. results.push(item);
  17855. }
  17856. if (!directDescendantsOnly) {
  17857. item._getDescendants(results, false, predicate);
  17858. }
  17859. }
  17860. };
  17861. /**
  17862. * Will return all nodes that have this node as ascendant
  17863. * @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
  17864. * @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
  17865. * @return all children nodes of all types
  17866. */
  17867. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17868. var results = new Array();
  17869. this._getDescendants(results, directDescendantsOnly, predicate);
  17870. return results;
  17871. };
  17872. /**
  17873. * Get all child-meshes of this node
  17874. * @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
  17875. * @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
  17876. * @returns an array of {BABYLON.AbstractMesh}
  17877. */
  17878. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17879. var results = [];
  17880. this._getDescendants(results, directDescendantsOnly, function (node) {
  17881. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17882. });
  17883. return results;
  17884. };
  17885. /**
  17886. * Get all child-transformNodes of this node
  17887. * @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
  17888. * @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
  17889. * @returns an array of {BABYLON.TransformNode}
  17890. */
  17891. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17892. var results = [];
  17893. this._getDescendants(results, directDescendantsOnly, function (node) {
  17894. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17895. });
  17896. return results;
  17897. };
  17898. /**
  17899. * Get all direct children of this node
  17900. * @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
  17901. * @returns an array of {BABYLON.Node}
  17902. */
  17903. Node.prototype.getChildren = function (predicate) {
  17904. return this.getDescendants(true, predicate);
  17905. };
  17906. /** @hidden */
  17907. Node.prototype._setReady = function (state) {
  17908. if (state === this._isReady) {
  17909. return;
  17910. }
  17911. if (!state) {
  17912. this._isReady = false;
  17913. return;
  17914. }
  17915. if (this.onReady) {
  17916. this.onReady(this);
  17917. }
  17918. this._isReady = true;
  17919. };
  17920. /**
  17921. * Get an animation by name
  17922. * @param name defines the name of the animation to look for
  17923. * @returns null if not found else the requested animation
  17924. */
  17925. Node.prototype.getAnimationByName = function (name) {
  17926. for (var i = 0; i < this.animations.length; i++) {
  17927. var animation = this.animations[i];
  17928. if (animation.name === name) {
  17929. return animation;
  17930. }
  17931. }
  17932. return null;
  17933. };
  17934. /**
  17935. * Creates an animation range for this node
  17936. * @param name defines the name of the range
  17937. * @param from defines the starting key
  17938. * @param to defines the end key
  17939. */
  17940. Node.prototype.createAnimationRange = function (name, from, to) {
  17941. // check name not already in use
  17942. if (!this._ranges[name]) {
  17943. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17945. if (this.animations[i]) {
  17946. this.animations[i].createRange(name, from, to);
  17947. }
  17948. }
  17949. }
  17950. };
  17951. /**
  17952. * Delete a specific animation range
  17953. * @param name defines the name of the range to delete
  17954. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17955. */
  17956. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17957. if (deleteFrames === void 0) { deleteFrames = true; }
  17958. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17959. if (this.animations[i]) {
  17960. this.animations[i].deleteRange(name, deleteFrames);
  17961. }
  17962. }
  17963. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17964. };
  17965. /**
  17966. * Get an animation range by name
  17967. * @param name defines the name of the animation range to look for
  17968. * @returns null if not found else the requested animation range
  17969. */
  17970. Node.prototype.getAnimationRange = function (name) {
  17971. return this._ranges[name];
  17972. };
  17973. /**
  17974. * Will start the animation sequence
  17975. * @param name defines the range frames for animation sequence
  17976. * @param loop defines if the animation should loop (false by default)
  17977. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17978. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17979. * @returns the object created for this animation. If range does not exist, it will return null
  17980. */
  17981. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17982. var range = this.getAnimationRange(name);
  17983. if (!range) {
  17984. return null;
  17985. }
  17986. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17987. };
  17988. /**
  17989. * Serialize animation ranges into a JSON compatible object
  17990. * @returns serialization object
  17991. */
  17992. Node.prototype.serializeAnimationRanges = function () {
  17993. var serializationRanges = [];
  17994. for (var name in this._ranges) {
  17995. var localRange = this._ranges[name];
  17996. if (!localRange) {
  17997. continue;
  17998. }
  17999. var range = {};
  18000. range.name = name;
  18001. range.from = localRange.from;
  18002. range.to = localRange.to;
  18003. serializationRanges.push(range);
  18004. }
  18005. return serializationRanges;
  18006. };
  18007. /**
  18008. * Computes the world matrix of the node
  18009. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18010. * @returns the world matrix
  18011. */
  18012. Node.prototype.computeWorldMatrix = function (force) {
  18013. return BABYLON.Matrix.Identity();
  18014. };
  18015. /**
  18016. * Releases resources associated with this node.
  18017. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18018. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18019. */
  18020. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18021. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18022. if (!doNotRecurse) {
  18023. var nodes = this.getDescendants(true);
  18024. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18025. var node = nodes_1[_i];
  18026. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18027. }
  18028. }
  18029. else {
  18030. var transformNodes = this.getChildTransformNodes(true);
  18031. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18032. var transformNode = transformNodes_1[_a];
  18033. transformNode.parent = null;
  18034. transformNode.computeWorldMatrix(true);
  18035. }
  18036. }
  18037. this.parent = null;
  18038. // Callback
  18039. this.onDisposeObservable.notifyObservers(this);
  18040. this.onDisposeObservable.clear();
  18041. // Behaviors
  18042. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18043. var behavior = _c[_b];
  18044. behavior.detach();
  18045. }
  18046. this._behaviors = [];
  18047. this._isDisposed = true;
  18048. };
  18049. /**
  18050. * Parse animation range data from a serialization object and store them into a given node
  18051. * @param node defines where to store the animation ranges
  18052. * @param parsedNode defines the serialization object to read data from
  18053. * @param scene defines the hosting scene
  18054. */
  18055. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18056. if (parsedNode.ranges) {
  18057. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18058. var data = parsedNode.ranges[index];
  18059. node.createAnimationRange(data.name, data.from, data.to);
  18060. }
  18061. }
  18062. };
  18063. Node._NodeConstructors = {};
  18064. __decorate([
  18065. BABYLON.serialize()
  18066. ], Node.prototype, "name", void 0);
  18067. __decorate([
  18068. BABYLON.serialize()
  18069. ], Node.prototype, "id", void 0);
  18070. __decorate([
  18071. BABYLON.serialize()
  18072. ], Node.prototype, "uniqueId", void 0);
  18073. __decorate([
  18074. BABYLON.serialize()
  18075. ], Node.prototype, "state", void 0);
  18076. __decorate([
  18077. BABYLON.serialize()
  18078. ], Node.prototype, "metadata", void 0);
  18079. return Node;
  18080. }());
  18081. BABYLON.Node = Node;
  18082. })(BABYLON || (BABYLON = {}));
  18083. //# sourceMappingURL=babylon.node.js.map
  18084. var BABYLON;
  18085. (function (BABYLON) {
  18086. // This matrix is used as a value to reset the bounding box.
  18087. var _identityMatrix = BABYLON.Matrix.Identity();
  18088. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18089. var BoundingSphere = /** @class */ (function () {
  18090. /**
  18091. * Creates a new bounding sphere
  18092. * @param min defines the minimum vector (in local space)
  18093. * @param max defines the maximum vector (in local space)
  18094. */
  18095. function BoundingSphere(min, max) {
  18096. this.center = BABYLON.Vector3.Zero();
  18097. this.centerWorld = BABYLON.Vector3.Zero();
  18098. this.reConstruct(min, max);
  18099. }
  18100. /**
  18101. * Recreates the entire bounding sphere from scratch
  18102. * @param min defines the new minimum vector (in local space)
  18103. * @param max defines the new maximum vector (in local space)
  18104. */
  18105. BoundingSphere.prototype.reConstruct = function (min, max) {
  18106. this.minimum = min.clone();
  18107. this.maximum = max.clone();
  18108. var distance = BABYLON.Vector3.Distance(min, max);
  18109. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18110. this.radius = distance * 0.5;
  18111. this.centerWorld.set(0, 0, 0);
  18112. this._update(_identityMatrix);
  18113. };
  18114. /**
  18115. * Scale the current bounding sphere by applying a scale factor
  18116. * @param factor defines the scale factor to apply
  18117. * @returns the current bounding box
  18118. */
  18119. BoundingSphere.prototype.scale = function (factor) {
  18120. var newRadius = this.radius * factor;
  18121. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18122. var min = this.center.subtract(_tempRadiusVector);
  18123. var max = this.center.add(_tempRadiusVector);
  18124. this.reConstruct(min, max);
  18125. return this;
  18126. };
  18127. // Methods
  18128. /** @hidden */
  18129. BoundingSphere.prototype._update = function (world) {
  18130. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18131. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18132. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18133. };
  18134. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18135. for (var i = 0; i < 6; i++) {
  18136. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18137. return false;
  18138. }
  18139. return true;
  18140. };
  18141. BoundingSphere.prototype.intersectsPoint = function (point) {
  18142. var x = this.centerWorld.x - point.x;
  18143. var y = this.centerWorld.y - point.y;
  18144. var z = this.centerWorld.z - point.z;
  18145. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18146. if (this.radiusWorld < distance)
  18147. return false;
  18148. return true;
  18149. };
  18150. // Statics
  18151. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18152. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18153. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18154. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18155. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18156. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18157. return false;
  18158. return true;
  18159. };
  18160. return BoundingSphere;
  18161. }());
  18162. BABYLON.BoundingSphere = BoundingSphere;
  18163. })(BABYLON || (BABYLON = {}));
  18164. //# sourceMappingURL=babylon.boundingSphere.js.map
  18165. var BABYLON;
  18166. (function (BABYLON) {
  18167. var BoundingBox = /** @class */ (function () {
  18168. /**
  18169. * Creates a new bounding box
  18170. * @param min defines the minimum vector (in local space)
  18171. * @param max defines the maximum vector (in local space)
  18172. */
  18173. function BoundingBox(min, max) {
  18174. this.vectorsWorld = new Array();
  18175. this.reConstruct(min, max);
  18176. }
  18177. // Methods
  18178. /**
  18179. * Recreates the entire bounding box from scratch
  18180. * @param min defines the new minimum vector (in local space)
  18181. * @param max defines the new maximum vector (in local space)
  18182. */
  18183. BoundingBox.prototype.reConstruct = function (min, max) {
  18184. this.minimum = min.clone();
  18185. this.maximum = max.clone();
  18186. // Bounding vectors
  18187. this.vectors = [
  18188. this.minimum.clone(),
  18189. this.maximum.clone(),
  18190. this.minimum.clone(),
  18191. this.minimum.clone(),
  18192. this.minimum.clone(),
  18193. this.maximum.clone(),
  18194. this.maximum.clone(),
  18195. this.maximum.clone()
  18196. ];
  18197. this.vectors[2].x = this.maximum.x;
  18198. this.vectors[3].y = this.maximum.y;
  18199. this.vectors[4].z = this.maximum.z;
  18200. this.vectors[5].z = this.minimum.z;
  18201. this.vectors[6].x = this.minimum.x;
  18202. this.vectors[7].y = this.minimum.y;
  18203. // OBB
  18204. this.center = this.maximum.add(this.minimum).scale(0.5);
  18205. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18206. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18207. // World
  18208. for (var index = 0; index < this.vectors.length; index++) {
  18209. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18210. }
  18211. this.minimumWorld = BABYLON.Vector3.Zero();
  18212. this.maximumWorld = BABYLON.Vector3.Zero();
  18213. this.centerWorld = BABYLON.Vector3.Zero();
  18214. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18215. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18216. };
  18217. /**
  18218. * Scale the current bounding box by applying a scale factor
  18219. * @param factor defines the scale factor to apply
  18220. * @returns the current bounding box
  18221. */
  18222. BoundingBox.prototype.scale = function (factor) {
  18223. var diff = this.maximum.subtract(this.minimum);
  18224. var distance = diff.length() * factor;
  18225. diff.normalize();
  18226. var newRadius = diff.scale(distance / 2);
  18227. var min = this.center.subtract(newRadius);
  18228. var max = this.center.add(newRadius);
  18229. this.reConstruct(min, max);
  18230. return this;
  18231. };
  18232. BoundingBox.prototype.getWorldMatrix = function () {
  18233. return this._worldMatrix;
  18234. };
  18235. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18236. this._worldMatrix.copyFrom(matrix);
  18237. return this;
  18238. };
  18239. /** @hidden */
  18240. BoundingBox.prototype._update = function (world) {
  18241. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18242. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18243. for (var index = 0; index < this.vectors.length; index++) {
  18244. var v = this.vectorsWorld[index];
  18245. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18246. if (v.x < this.minimumWorld.x)
  18247. this.minimumWorld.x = v.x;
  18248. if (v.y < this.minimumWorld.y)
  18249. this.minimumWorld.y = v.y;
  18250. if (v.z < this.minimumWorld.z)
  18251. this.minimumWorld.z = v.z;
  18252. if (v.x > this.maximumWorld.x)
  18253. this.maximumWorld.x = v.x;
  18254. if (v.y > this.maximumWorld.y)
  18255. this.maximumWorld.y = v.y;
  18256. if (v.z > this.maximumWorld.z)
  18257. this.maximumWorld.z = v.z;
  18258. }
  18259. // Extend
  18260. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18261. this.extendSizeWorld.scaleInPlace(0.5);
  18262. // OBB
  18263. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18264. this.centerWorld.scaleInPlace(0.5);
  18265. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18266. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18267. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18268. this._worldMatrix = world;
  18269. };
  18270. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18271. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18272. };
  18273. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18274. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18275. };
  18276. BoundingBox.prototype.intersectsPoint = function (point) {
  18277. var delta = -BABYLON.Epsilon;
  18278. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18279. return false;
  18280. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18281. return false;
  18282. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18283. return false;
  18284. return true;
  18285. };
  18286. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18287. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18288. };
  18289. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18290. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18291. return false;
  18292. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18293. return false;
  18294. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18295. return false;
  18296. return true;
  18297. };
  18298. // Statics
  18299. BoundingBox.Intersects = function (box0, box1) {
  18300. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18301. return false;
  18302. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18303. return false;
  18304. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18305. return false;
  18306. return true;
  18307. };
  18308. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18309. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18310. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18311. return (num <= (sphereRadius * sphereRadius));
  18312. };
  18313. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18314. for (var p = 0; p < 6; p++) {
  18315. for (var i = 0; i < 8; i++) {
  18316. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18317. return false;
  18318. }
  18319. }
  18320. }
  18321. return true;
  18322. };
  18323. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18324. for (var p = 0; p < 6; p++) {
  18325. var inCount = 8;
  18326. for (var i = 0; i < 8; i++) {
  18327. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18328. --inCount;
  18329. }
  18330. else {
  18331. break;
  18332. }
  18333. }
  18334. if (inCount === 0)
  18335. return false;
  18336. }
  18337. return true;
  18338. };
  18339. return BoundingBox;
  18340. }());
  18341. BABYLON.BoundingBox = BoundingBox;
  18342. })(BABYLON || (BABYLON = {}));
  18343. //# sourceMappingURL=babylon.boundingBox.js.map
  18344. var BABYLON;
  18345. (function (BABYLON) {
  18346. var computeBoxExtents = function (axis, box) {
  18347. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18348. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18349. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18350. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18351. var r = r0 + r1 + r2;
  18352. return {
  18353. min: p - r,
  18354. max: p + r
  18355. };
  18356. };
  18357. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18358. var axisOverlap = function (axis, box0, box1) {
  18359. var result0 = computeBoxExtents(axis, box0);
  18360. var result1 = computeBoxExtents(axis, box1);
  18361. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18362. };
  18363. var BoundingInfo = /** @class */ (function () {
  18364. function BoundingInfo(minimum, maximum) {
  18365. this.minimum = minimum;
  18366. this.maximum = maximum;
  18367. this._isLocked = false;
  18368. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18369. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18370. }
  18371. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18372. get: function () {
  18373. return this._isLocked;
  18374. },
  18375. set: function (value) {
  18376. this._isLocked = value;
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. // Methods
  18382. BoundingInfo.prototype.update = function (world) {
  18383. if (this._isLocked) {
  18384. return;
  18385. }
  18386. this.boundingBox._update(world);
  18387. this.boundingSphere._update(world);
  18388. };
  18389. /**
  18390. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18391. * @param center New center of the bounding info
  18392. * @param extend New extend of the bounding info
  18393. */
  18394. BoundingInfo.prototype.centerOn = function (center, extend) {
  18395. this.minimum = center.subtract(extend);
  18396. this.maximum = center.add(extend);
  18397. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18398. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18399. return this;
  18400. };
  18401. /**
  18402. * Scale the current bounding info by applying a scale factor
  18403. * @param factor defines the scale factor to apply
  18404. * @returns the current bounding info
  18405. */
  18406. BoundingInfo.prototype.scale = function (factor) {
  18407. this.boundingBox.scale(factor);
  18408. this.boundingSphere.scale(factor);
  18409. return this;
  18410. };
  18411. /**
  18412. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18413. * @param frustumPlanes defines the frustum to test
  18414. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18415. * @returns true if the bounding info is in the frustum planes
  18416. */
  18417. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18418. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18419. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18420. return false;
  18421. }
  18422. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18423. return true;
  18424. }
  18425. return this.boundingBox.isInFrustum(frustumPlanes);
  18426. };
  18427. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18428. /**
  18429. * Gets the world distance between the min and max points of the bounding box
  18430. */
  18431. get: function () {
  18432. var boundingBox = this.boundingBox;
  18433. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18434. return size.length();
  18435. },
  18436. enumerable: true,
  18437. configurable: true
  18438. });
  18439. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18440. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18441. };
  18442. /** @hidden */
  18443. BoundingInfo.prototype._checkCollision = function (collider) {
  18444. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18445. };
  18446. BoundingInfo.prototype.intersectsPoint = function (point) {
  18447. if (!this.boundingSphere.centerWorld) {
  18448. return false;
  18449. }
  18450. if (!this.boundingSphere.intersectsPoint(point)) {
  18451. return false;
  18452. }
  18453. if (!this.boundingBox.intersectsPoint(point)) {
  18454. return false;
  18455. }
  18456. return true;
  18457. };
  18458. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18459. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18460. return false;
  18461. }
  18462. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18463. return false;
  18464. }
  18465. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18466. return false;
  18467. }
  18468. if (!precise) {
  18469. return true;
  18470. }
  18471. var box0 = this.boundingBox;
  18472. var box1 = boundingInfo.boundingBox;
  18473. if (!axisOverlap(box0.directions[0], box0, box1))
  18474. return false;
  18475. if (!axisOverlap(box0.directions[1], box0, box1))
  18476. return false;
  18477. if (!axisOverlap(box0.directions[2], box0, box1))
  18478. return false;
  18479. if (!axisOverlap(box1.directions[0], box0, box1))
  18480. return false;
  18481. if (!axisOverlap(box1.directions[1], box0, box1))
  18482. return false;
  18483. if (!axisOverlap(box1.directions[2], box0, box1))
  18484. return false;
  18485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18486. return false;
  18487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18488. return false;
  18489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18490. return false;
  18491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18492. return false;
  18493. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18494. return false;
  18495. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18496. return false;
  18497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18498. return false;
  18499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18500. return false;
  18501. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18502. return false;
  18503. return true;
  18504. };
  18505. return BoundingInfo;
  18506. }());
  18507. BABYLON.BoundingInfo = BoundingInfo;
  18508. })(BABYLON || (BABYLON = {}));
  18509. //# sourceMappingURL=babylon.boundingInfo.js.map
  18510. var BABYLON;
  18511. (function (BABYLON) {
  18512. var TransformNode = /** @class */ (function (_super) {
  18513. __extends(TransformNode, _super);
  18514. function TransformNode(name, scene, isPure) {
  18515. if (scene === void 0) { scene = null; }
  18516. if (isPure === void 0) { isPure = true; }
  18517. var _this = _super.call(this, name, scene) || this;
  18518. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18519. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18520. _this._up = new BABYLON.Vector3(0, 1, 0);
  18521. _this._right = new BABYLON.Vector3(1, 0, 0);
  18522. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18523. // Properties
  18524. _this._rotation = BABYLON.Vector3.Zero();
  18525. _this._scaling = BABYLON.Vector3.One();
  18526. _this._isDirty = false;
  18527. /**
  18528. * Set the billboard mode. Default is 0.
  18529. *
  18530. * | Value | Type | Description |
  18531. * | --- | --- | --- |
  18532. * | 0 | BILLBOARDMODE_NONE | |
  18533. * | 1 | BILLBOARDMODE_X | |
  18534. * | 2 | BILLBOARDMODE_Y | |
  18535. * | 4 | BILLBOARDMODE_Z | |
  18536. * | 7 | BILLBOARDMODE_ALL | |
  18537. *
  18538. */
  18539. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18540. _this.scalingDeterminant = 1;
  18541. _this.infiniteDistance = false;
  18542. /**
  18543. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18544. * By default the system will update normals to compensate
  18545. */
  18546. _this.ignoreNonUniformScaling = false;
  18547. _this.position = BABYLON.Vector3.Zero();
  18548. _this._localWorld = BABYLON.Matrix.Zero();
  18549. /** @hidden */
  18550. _this._worldMatrix = BABYLON.Matrix.Zero();
  18551. /** @hidden */
  18552. _this._worldMatrixDeterminant = 0;
  18553. _this._absolutePosition = BABYLON.Vector3.Zero();
  18554. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18555. _this._postMultiplyPivotMatrix = false;
  18556. _this._isWorldMatrixFrozen = false;
  18557. /**
  18558. * An event triggered after the world matrix is updated
  18559. */
  18560. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18561. _this._nonUniformScaling = false;
  18562. if (isPure) {
  18563. _this.getScene().addTransformNode(_this);
  18564. }
  18565. return _this;
  18566. }
  18567. /**
  18568. * Gets a string identifying the name of the class
  18569. * @returns "TransformNode" string
  18570. */
  18571. TransformNode.prototype.getClassName = function () {
  18572. return "TransformNode";
  18573. };
  18574. Object.defineProperty(TransformNode.prototype, "rotation", {
  18575. /**
  18576. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18577. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18578. * Default : (0.0, 0.0, 0.0)
  18579. */
  18580. get: function () {
  18581. return this._rotation;
  18582. },
  18583. set: function (newRotation) {
  18584. this._rotation = newRotation;
  18585. },
  18586. enumerable: true,
  18587. configurable: true
  18588. });
  18589. Object.defineProperty(TransformNode.prototype, "scaling", {
  18590. /**
  18591. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18592. * Default : (1.0, 1.0, 1.0)
  18593. */
  18594. get: function () {
  18595. return this._scaling;
  18596. },
  18597. /**
  18598. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18599. * Default : (1.0, 1.0, 1.0)
  18600. */
  18601. set: function (newScaling) {
  18602. this._scaling = newScaling;
  18603. },
  18604. enumerable: true,
  18605. configurable: true
  18606. });
  18607. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18608. /**
  18609. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18610. * It's null by default.
  18611. * 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)
  18612. */
  18613. get: function () {
  18614. return this._rotationQuaternion;
  18615. },
  18616. set: function (quaternion) {
  18617. this._rotationQuaternion = quaternion;
  18618. //reset the rotation vector.
  18619. if (quaternion && this.rotation.length()) {
  18620. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18621. }
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. Object.defineProperty(TransformNode.prototype, "forward", {
  18627. /**
  18628. * The forward direction of that transform in world space.
  18629. */
  18630. get: function () {
  18631. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18632. },
  18633. enumerable: true,
  18634. configurable: true
  18635. });
  18636. Object.defineProperty(TransformNode.prototype, "up", {
  18637. /**
  18638. * The up direction of that transform in world space.
  18639. */
  18640. get: function () {
  18641. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. Object.defineProperty(TransformNode.prototype, "right", {
  18647. /**
  18648. * The right direction of that transform in world space.
  18649. */
  18650. get: function () {
  18651. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18652. },
  18653. enumerable: true,
  18654. configurable: true
  18655. });
  18656. /**
  18657. * Returns the latest update of the World matrix
  18658. * Returns a Matrix.
  18659. */
  18660. TransformNode.prototype.getWorldMatrix = function () {
  18661. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18662. this.computeWorldMatrix();
  18663. }
  18664. return this._worldMatrix;
  18665. };
  18666. /** @hidden */
  18667. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18668. return this._worldMatrixDeterminant;
  18669. };
  18670. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18671. /**
  18672. * Returns directly the latest state of the mesh World matrix.
  18673. * A Matrix is returned.
  18674. */
  18675. get: function () {
  18676. return this._worldMatrix;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. /**
  18682. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18683. * Returns the TransformNode.
  18684. */
  18685. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18686. this._poseMatrix.copyFrom(matrix);
  18687. return this;
  18688. };
  18689. /**
  18690. * Returns the mesh Pose matrix.
  18691. * Returned object : Matrix
  18692. */
  18693. TransformNode.prototype.getPoseMatrix = function () {
  18694. return this._poseMatrix;
  18695. };
  18696. /** @hidden */
  18697. TransformNode.prototype._isSynchronized = function () {
  18698. if (this._isDirty) {
  18699. return false;
  18700. }
  18701. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18702. return false;
  18703. if (this._cache.pivotMatrixUpdated) {
  18704. return false;
  18705. }
  18706. if (this.infiniteDistance) {
  18707. return false;
  18708. }
  18709. if (!this._cache.position.equals(this.position))
  18710. return false;
  18711. if (this._rotationQuaternion) {
  18712. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18713. return false;
  18714. }
  18715. if (!this._cache.rotation.equals(this.rotation))
  18716. return false;
  18717. if (!this._cache.scaling.equals(this.scaling))
  18718. return false;
  18719. return true;
  18720. };
  18721. /** @hidden */
  18722. TransformNode.prototype._initCache = function () {
  18723. _super.prototype._initCache.call(this);
  18724. this._cache.localMatrixUpdated = false;
  18725. this._cache.position = BABYLON.Vector3.Zero();
  18726. this._cache.scaling = BABYLON.Vector3.Zero();
  18727. this._cache.rotation = BABYLON.Vector3.Zero();
  18728. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18729. this._cache.billboardMode = -1;
  18730. };
  18731. TransformNode.prototype.markAsDirty = function (property) {
  18732. if (property === "rotation") {
  18733. this.rotationQuaternion = null;
  18734. }
  18735. this._currentRenderId = Number.MAX_VALUE;
  18736. this._isDirty = true;
  18737. return this;
  18738. };
  18739. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18740. /**
  18741. * Returns the current mesh absolute position.
  18742. * Returns a Vector3.
  18743. */
  18744. get: function () {
  18745. return this._absolutePosition;
  18746. },
  18747. enumerable: true,
  18748. configurable: true
  18749. });
  18750. /**
  18751. * Sets a new matrix to apply before all other transformation
  18752. * @param matrix defines the transform matrix
  18753. * @returns the current TransformNode
  18754. */
  18755. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18756. return this.setPivotMatrix(matrix, false);
  18757. };
  18758. /**
  18759. * Sets a new pivot matrix to the current node
  18760. * @param matrix defines the new pivot matrix to use
  18761. * @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
  18762. * @returns the current TransformNode
  18763. */
  18764. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18765. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18766. this._pivotMatrix = matrix.clone();
  18767. this._cache.pivotMatrixUpdated = true;
  18768. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18769. if (this._postMultiplyPivotMatrix) {
  18770. if (!this._pivotMatrixInverse) {
  18771. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18772. }
  18773. else {
  18774. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18775. }
  18776. }
  18777. return this;
  18778. };
  18779. /**
  18780. * Returns the mesh pivot matrix.
  18781. * Default : Identity.
  18782. * A Matrix is returned.
  18783. */
  18784. TransformNode.prototype.getPivotMatrix = function () {
  18785. return this._pivotMatrix;
  18786. };
  18787. /**
  18788. * Prevents the World matrix to be computed any longer.
  18789. * Returns the TransformNode.
  18790. */
  18791. TransformNode.prototype.freezeWorldMatrix = function () {
  18792. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18793. this.computeWorldMatrix(true);
  18794. this._isWorldMatrixFrozen = true;
  18795. return this;
  18796. };
  18797. /**
  18798. * Allows back the World matrix computation.
  18799. * Returns the TransformNode.
  18800. */
  18801. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18802. this._isWorldMatrixFrozen = false;
  18803. this.computeWorldMatrix(true);
  18804. return this;
  18805. };
  18806. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18807. /**
  18808. * True if the World matrix has been frozen.
  18809. * Returns a boolean.
  18810. */
  18811. get: function () {
  18812. return this._isWorldMatrixFrozen;
  18813. },
  18814. enumerable: true,
  18815. configurable: true
  18816. });
  18817. /**
  18818. * Retuns the mesh absolute position in the World.
  18819. * Returns a Vector3.
  18820. */
  18821. TransformNode.prototype.getAbsolutePosition = function () {
  18822. this.computeWorldMatrix();
  18823. return this._absolutePosition;
  18824. };
  18825. /**
  18826. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18827. * Returns the TransformNode.
  18828. */
  18829. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18830. if (!absolutePosition) {
  18831. return this;
  18832. }
  18833. var absolutePositionX;
  18834. var absolutePositionY;
  18835. var absolutePositionZ;
  18836. if (absolutePosition.x === undefined) {
  18837. if (arguments.length < 3) {
  18838. return this;
  18839. }
  18840. absolutePositionX = arguments[0];
  18841. absolutePositionY = arguments[1];
  18842. absolutePositionZ = arguments[2];
  18843. }
  18844. else {
  18845. absolutePositionX = absolutePosition.x;
  18846. absolutePositionY = absolutePosition.y;
  18847. absolutePositionZ = absolutePosition.z;
  18848. }
  18849. if (this.parent) {
  18850. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18851. invertParentWorldMatrix.invert();
  18852. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18853. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18854. }
  18855. else {
  18856. this.position.x = absolutePositionX;
  18857. this.position.y = absolutePositionY;
  18858. this.position.z = absolutePositionZ;
  18859. }
  18860. return this;
  18861. };
  18862. /**
  18863. * Sets the mesh position in its local space.
  18864. * Returns the TransformNode.
  18865. */
  18866. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18867. this.computeWorldMatrix();
  18868. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18869. return this;
  18870. };
  18871. /**
  18872. * Returns the mesh position in the local space from the current World matrix values.
  18873. * Returns a new Vector3.
  18874. */
  18875. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18876. this.computeWorldMatrix();
  18877. var invLocalWorldMatrix = this._localWorld.clone();
  18878. invLocalWorldMatrix.invert();
  18879. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18880. };
  18881. /**
  18882. * Translates the mesh along the passed Vector3 in its local space.
  18883. * Returns the TransformNode.
  18884. */
  18885. TransformNode.prototype.locallyTranslate = function (vector3) {
  18886. this.computeWorldMatrix(true);
  18887. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18888. return this;
  18889. };
  18890. /**
  18891. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18892. * @param targetPoint the position (must be in same space as current mesh) to look at
  18893. * @param yawCor optional yaw (y-axis) correction in radians
  18894. * @param pitchCor optional pitch (x-axis) correction in radians
  18895. * @param rollCor optional roll (z-axis) correction in radians
  18896. * @param space the choosen space of the target
  18897. * @returns the TransformNode.
  18898. */
  18899. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18900. if (yawCor === void 0) { yawCor = 0; }
  18901. if (pitchCor === void 0) { pitchCor = 0; }
  18902. if (rollCor === void 0) { rollCor = 0; }
  18903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18904. var dv = TransformNode._lookAtVectorCache;
  18905. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18906. targetPoint.subtractToRef(pos, dv);
  18907. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18908. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18909. var pitch = Math.atan2(dv.y, len);
  18910. if (this.rotationQuaternion) {
  18911. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18912. }
  18913. else {
  18914. this.rotation.x = pitch + pitchCor;
  18915. this.rotation.y = yaw + yawCor;
  18916. this.rotation.z = rollCor;
  18917. }
  18918. return this;
  18919. };
  18920. /**
  18921. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18922. * This Vector3 is expressed in the World space.
  18923. */
  18924. TransformNode.prototype.getDirection = function (localAxis) {
  18925. var result = BABYLON.Vector3.Zero();
  18926. this.getDirectionToRef(localAxis, result);
  18927. return result;
  18928. };
  18929. /**
  18930. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18931. * localAxis is expressed in the mesh local space.
  18932. * result is computed in the Wordl space from the mesh World matrix.
  18933. * Returns the TransformNode.
  18934. */
  18935. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18936. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18937. return this;
  18938. };
  18939. /**
  18940. * Sets a new pivot point to the current node
  18941. * @param point defines the new pivot point to use
  18942. * @param space defines if the point is in world or local space (local by default)
  18943. * @returns the current TransformNode
  18944. */
  18945. TransformNode.prototype.setPivotPoint = function (point, space) {
  18946. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18947. if (this.getScene().getRenderId() == 0) {
  18948. this.computeWorldMatrix(true);
  18949. }
  18950. var wm = this.getWorldMatrix();
  18951. if (space == BABYLON.Space.WORLD) {
  18952. var tmat = BABYLON.Tmp.Matrix[0];
  18953. wm.invertToRef(tmat);
  18954. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18955. }
  18956. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18957. };
  18958. /**
  18959. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18960. */
  18961. TransformNode.prototype.getPivotPoint = function () {
  18962. var point = BABYLON.Vector3.Zero();
  18963. this.getPivotPointToRef(point);
  18964. return point;
  18965. };
  18966. /**
  18967. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18968. * Returns the TransformNode.
  18969. */
  18970. TransformNode.prototype.getPivotPointToRef = function (result) {
  18971. result.x = -this._pivotMatrix.m[12];
  18972. result.y = -this._pivotMatrix.m[13];
  18973. result.z = -this._pivotMatrix.m[14];
  18974. return this;
  18975. };
  18976. /**
  18977. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18978. */
  18979. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18980. var point = BABYLON.Vector3.Zero();
  18981. this.getAbsolutePivotPointToRef(point);
  18982. return point;
  18983. };
  18984. /**
  18985. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18986. * Returns the TransformNode.
  18987. */
  18988. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18989. result.x = this._pivotMatrix.m[12];
  18990. result.y = this._pivotMatrix.m[13];
  18991. result.z = this._pivotMatrix.m[14];
  18992. this.getPivotPointToRef(result);
  18993. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18994. return this;
  18995. };
  18996. /**
  18997. * Defines the passed node as the parent of the current node.
  18998. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18999. * Returns the TransformNode.
  19000. */
  19001. TransformNode.prototype.setParent = function (node) {
  19002. if (!node && !this.parent) {
  19003. return this;
  19004. }
  19005. if (!node) {
  19006. var rotation = BABYLON.Tmp.Quaternion[0];
  19007. var position = BABYLON.Tmp.Vector3[0];
  19008. var scale = BABYLON.Tmp.Vector3[1];
  19009. if (this.parent && this.parent.computeWorldMatrix) {
  19010. this.parent.computeWorldMatrix(true);
  19011. }
  19012. this.computeWorldMatrix(true);
  19013. this.getWorldMatrix().decompose(scale, rotation, position);
  19014. if (this.rotationQuaternion) {
  19015. this.rotationQuaternion.copyFrom(rotation);
  19016. }
  19017. else {
  19018. rotation.toEulerAnglesToRef(this.rotation);
  19019. }
  19020. this.scaling.x = scale.x;
  19021. this.scaling.y = scale.y;
  19022. this.scaling.z = scale.z;
  19023. this.position.x = position.x;
  19024. this.position.y = position.y;
  19025. this.position.z = position.z;
  19026. }
  19027. else {
  19028. var rotation = BABYLON.Tmp.Quaternion[0];
  19029. var position = BABYLON.Tmp.Vector3[0];
  19030. var scale = BABYLON.Tmp.Vector3[1];
  19031. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19032. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19033. this.computeWorldMatrix(true);
  19034. node.computeWorldMatrix(true);
  19035. node.getWorldMatrix().invertToRef(invParentMatrix);
  19036. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19037. diffMatrix.decompose(scale, rotation, position);
  19038. if (this.rotationQuaternion) {
  19039. this.rotationQuaternion.copyFrom(rotation);
  19040. }
  19041. else {
  19042. rotation.toEulerAnglesToRef(this.rotation);
  19043. }
  19044. this.position.x = position.x;
  19045. this.position.y = position.y;
  19046. this.position.z = position.z;
  19047. this.scaling.x = scale.x;
  19048. this.scaling.y = scale.y;
  19049. this.scaling.z = scale.z;
  19050. }
  19051. this.parent = node;
  19052. return this;
  19053. };
  19054. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19055. get: function () {
  19056. return this._nonUniformScaling;
  19057. },
  19058. enumerable: true,
  19059. configurable: true
  19060. });
  19061. /** @hidden */
  19062. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19063. if (this._nonUniformScaling === value) {
  19064. return false;
  19065. }
  19066. this._nonUniformScaling = value;
  19067. return true;
  19068. };
  19069. /**
  19070. * Attach the current TransformNode to another TransformNode associated with a bone
  19071. * @param bone Bone affecting the TransformNode
  19072. * @param affectedTransformNode TransformNode associated with the bone
  19073. */
  19074. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19075. this._transformToBoneReferal = affectedTransformNode;
  19076. this.parent = bone;
  19077. if (bone.getWorldMatrix().determinant() < 0) {
  19078. this.scalingDeterminant *= -1;
  19079. }
  19080. return this;
  19081. };
  19082. TransformNode.prototype.detachFromBone = function () {
  19083. if (!this.parent) {
  19084. return this;
  19085. }
  19086. if (this.parent.getWorldMatrix().determinant() < 0) {
  19087. this.scalingDeterminant *= -1;
  19088. }
  19089. this._transformToBoneReferal = null;
  19090. this.parent = null;
  19091. return this;
  19092. };
  19093. /**
  19094. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19095. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19096. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19097. * The passed axis is also normalized.
  19098. * Returns the TransformNode.
  19099. */
  19100. TransformNode.prototype.rotate = function (axis, amount, space) {
  19101. axis.normalize();
  19102. if (!this.rotationQuaternion) {
  19103. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19104. this.rotation = BABYLON.Vector3.Zero();
  19105. }
  19106. var rotationQuaternion;
  19107. if (!space || space === BABYLON.Space.LOCAL) {
  19108. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19109. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19110. }
  19111. else {
  19112. if (this.parent) {
  19113. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19114. invertParentWorldMatrix.invert();
  19115. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19116. }
  19117. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19118. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19119. }
  19120. return this;
  19121. };
  19122. /**
  19123. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19124. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19125. * The passed axis is also normalized.
  19126. * Returns the TransformNode.
  19127. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19128. */
  19129. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19130. axis.normalize();
  19131. if (!this.rotationQuaternion) {
  19132. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19133. this.rotation.copyFromFloats(0, 0, 0);
  19134. }
  19135. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19136. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19137. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19138. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19139. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19140. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19141. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19142. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19143. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19144. return this;
  19145. };
  19146. /**
  19147. * Translates the mesh along the axis vector for the passed distance in the given space.
  19148. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19149. * Returns the TransformNode.
  19150. */
  19151. TransformNode.prototype.translate = function (axis, distance, space) {
  19152. var displacementVector = axis.scale(distance);
  19153. if (!space || space === BABYLON.Space.LOCAL) {
  19154. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19155. this.setPositionWithLocalVector(tempV3);
  19156. }
  19157. else {
  19158. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19159. }
  19160. return this;
  19161. };
  19162. /**
  19163. * Adds a rotation step to the mesh current rotation.
  19164. * x, y, z are Euler angles expressed in radians.
  19165. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19166. * This means this rotation is made in the mesh local space only.
  19167. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19168. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19169. * ```javascript
  19170. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19171. * ```
  19172. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19173. * 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.
  19174. * Returns the TransformNode.
  19175. */
  19176. TransformNode.prototype.addRotation = function (x, y, z) {
  19177. var rotationQuaternion;
  19178. if (this.rotationQuaternion) {
  19179. rotationQuaternion = this.rotationQuaternion;
  19180. }
  19181. else {
  19182. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19183. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19184. }
  19185. var accumulation = BABYLON.Tmp.Quaternion[0];
  19186. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19187. rotationQuaternion.multiplyInPlace(accumulation);
  19188. if (!this.rotationQuaternion) {
  19189. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19190. }
  19191. return this;
  19192. };
  19193. /**
  19194. * Computes the mesh World matrix and returns it.
  19195. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19196. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19197. * If the parameter `force`is set to `true`, the actual computation is done.
  19198. * Returns the mesh World Matrix.
  19199. */
  19200. TransformNode.prototype.computeWorldMatrix = function (force) {
  19201. if (this._isWorldMatrixFrozen) {
  19202. return this._worldMatrix;
  19203. }
  19204. if (!force && this.isSynchronized(true)) {
  19205. this._currentRenderId = this.getScene().getRenderId();
  19206. return this._worldMatrix;
  19207. }
  19208. this._cache.position.copyFrom(this.position);
  19209. this._cache.scaling.copyFrom(this.scaling);
  19210. this._cache.pivotMatrixUpdated = false;
  19211. this._cache.billboardMode = this.billboardMode;
  19212. this._currentRenderId = this.getScene().getRenderId();
  19213. this._childRenderId = this.getScene().getRenderId();
  19214. this._isDirty = false;
  19215. // Scaling
  19216. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19217. // Rotation
  19218. //rotate, if quaternion is set and rotation was used
  19219. if (this.rotationQuaternion) {
  19220. var len = this.rotation.length();
  19221. if (len) {
  19222. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19223. this.rotation.copyFromFloats(0, 0, 0);
  19224. }
  19225. }
  19226. if (this.rotationQuaternion) {
  19227. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19228. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19229. }
  19230. else {
  19231. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19232. this._cache.rotation.copyFrom(this.rotation);
  19233. }
  19234. // Translation
  19235. var camera = this.getScene().activeCamera;
  19236. if (this.infiniteDistance && !this.parent && camera) {
  19237. var cameraWorldMatrix = camera.getWorldMatrix();
  19238. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19239. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19240. }
  19241. else {
  19242. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19243. }
  19244. // Composing transformations
  19245. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19246. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19247. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19248. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19249. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19250. // Need to decompose each rotation here
  19251. var currentPosition = BABYLON.Tmp.Vector3[3];
  19252. if (this.parent && this.parent.getWorldMatrix) {
  19253. if (this._transformToBoneReferal) {
  19254. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19255. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19256. }
  19257. else {
  19258. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19259. }
  19260. }
  19261. else {
  19262. currentPosition.copyFrom(this.position);
  19263. }
  19264. currentPosition.subtractInPlace(camera.globalPosition);
  19265. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19266. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19267. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19268. }
  19269. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19270. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19271. }
  19272. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19273. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19274. }
  19275. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19276. }
  19277. else {
  19278. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19279. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19280. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19281. }
  19282. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19283. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19284. }
  19285. // Post multiply inverse of pivotMatrix
  19286. if (this._postMultiplyPivotMatrix) {
  19287. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19288. }
  19289. // Local world
  19290. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19291. // Parent
  19292. if (this.parent && this.parent.getWorldMatrix) {
  19293. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19294. if (this._transformToBoneReferal) {
  19295. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19296. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19297. }
  19298. else {
  19299. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19300. }
  19301. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19302. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19303. this._worldMatrix.copyFrom(this._localWorld);
  19304. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19305. }
  19306. else {
  19307. if (this._transformToBoneReferal) {
  19308. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19309. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19310. }
  19311. else {
  19312. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19313. }
  19314. }
  19315. this._markSyncedWithParent();
  19316. }
  19317. else {
  19318. this._worldMatrix.copyFrom(this._localWorld);
  19319. }
  19320. // Normal matrix
  19321. if (!this.ignoreNonUniformScaling) {
  19322. if (this.scaling.isNonUniform) {
  19323. this._updateNonUniformScalingState(true);
  19324. }
  19325. else if (this.parent && this.parent._nonUniformScaling) {
  19326. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19327. }
  19328. else {
  19329. this._updateNonUniformScalingState(false);
  19330. }
  19331. }
  19332. else {
  19333. this._updateNonUniformScalingState(false);
  19334. }
  19335. this._afterComputeWorldMatrix();
  19336. // Absolute position
  19337. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19338. // Callbacks
  19339. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19340. if (!this._poseMatrix) {
  19341. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19342. }
  19343. // Cache the determinant
  19344. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19345. return this._worldMatrix;
  19346. };
  19347. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19348. };
  19349. /**
  19350. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19351. * @param func: callback function to add
  19352. *
  19353. * Returns the TransformNode.
  19354. */
  19355. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19356. this.onAfterWorldMatrixUpdateObservable.add(func);
  19357. return this;
  19358. };
  19359. /**
  19360. * Removes a registered callback function.
  19361. * Returns the TransformNode.
  19362. */
  19363. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19364. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19365. return this;
  19366. };
  19367. /**
  19368. * Clone the current transform node
  19369. * Returns the new transform node
  19370. * @param name Name of the new clone
  19371. * @param newParent New parent for the clone
  19372. * @param doNotCloneChildren Do not clone children hierarchy
  19373. */
  19374. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19375. var _this = this;
  19376. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19377. result.name = name;
  19378. result.id = name;
  19379. if (newParent) {
  19380. result.parent = newParent;
  19381. }
  19382. if (!doNotCloneChildren) {
  19383. // Children
  19384. var directDescendants = this.getDescendants(true);
  19385. for (var index = 0; index < directDescendants.length; index++) {
  19386. var child = directDescendants[index];
  19387. if (child.clone) {
  19388. child.clone(name + "." + child.name, result);
  19389. }
  19390. }
  19391. }
  19392. return result;
  19393. };
  19394. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19395. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19396. serializationObject.type = this.getClassName();
  19397. // Parent
  19398. if (this.parent) {
  19399. serializationObject.parentId = this.parent.id;
  19400. }
  19401. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19402. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19403. }
  19404. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19405. serializationObject.isEnabled = this.isEnabled();
  19406. // Parent
  19407. if (this.parent) {
  19408. serializationObject.parentId = this.parent.id;
  19409. }
  19410. return serializationObject;
  19411. };
  19412. // Statics
  19413. /**
  19414. * Returns a new TransformNode object parsed from the source provided.
  19415. * The parameter `parsedMesh` is the source.
  19416. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19417. */
  19418. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19419. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19420. if (BABYLON.Tags) {
  19421. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19422. }
  19423. if (parsedTransformNode.localMatrix) {
  19424. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19425. }
  19426. else if (parsedTransformNode.pivotMatrix) {
  19427. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19428. }
  19429. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19430. // Parent
  19431. if (parsedTransformNode.parentId) {
  19432. transformNode._waitingParentId = parsedTransformNode.parentId;
  19433. }
  19434. return transformNode;
  19435. };
  19436. /**
  19437. * Releases resources associated with this transform node.
  19438. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19439. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19440. */
  19441. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19442. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19443. // Animations
  19444. this.getScene().stopAnimation(this);
  19445. // Remove from scene
  19446. this.getScene().removeTransformNode(this);
  19447. this.onAfterWorldMatrixUpdateObservable.clear();
  19448. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19449. };
  19450. // Statics
  19451. TransformNode.BILLBOARDMODE_NONE = 0;
  19452. TransformNode.BILLBOARDMODE_X = 1;
  19453. TransformNode.BILLBOARDMODE_Y = 2;
  19454. TransformNode.BILLBOARDMODE_Z = 4;
  19455. TransformNode.BILLBOARDMODE_ALL = 7;
  19456. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19457. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19458. __decorate([
  19459. BABYLON.serializeAsVector3()
  19460. ], TransformNode.prototype, "_rotation", void 0);
  19461. __decorate([
  19462. BABYLON.serializeAsQuaternion()
  19463. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19464. __decorate([
  19465. BABYLON.serializeAsVector3()
  19466. ], TransformNode.prototype, "_scaling", void 0);
  19467. __decorate([
  19468. BABYLON.serialize()
  19469. ], TransformNode.prototype, "billboardMode", void 0);
  19470. __decorate([
  19471. BABYLON.serialize()
  19472. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19473. __decorate([
  19474. BABYLON.serialize()
  19475. ], TransformNode.prototype, "infiniteDistance", void 0);
  19476. __decorate([
  19477. BABYLON.serialize()
  19478. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19479. __decorate([
  19480. BABYLON.serializeAsVector3()
  19481. ], TransformNode.prototype, "position", void 0);
  19482. return TransformNode;
  19483. }(BABYLON.Node));
  19484. BABYLON.TransformNode = TransformNode;
  19485. })(BABYLON || (BABYLON = {}));
  19486. //# sourceMappingURL=babylon.transformNode.js.map
  19487. var BABYLON;
  19488. (function (BABYLON) {
  19489. /**
  19490. * Class used to store all common mesh properties
  19491. */
  19492. var AbstractMesh = /** @class */ (function (_super) {
  19493. __extends(AbstractMesh, _super);
  19494. // Constructor
  19495. /**
  19496. * Creates a new AbstractMesh
  19497. * @param name defines the name of the mesh
  19498. * @param scene defines the hosting scene
  19499. */
  19500. function AbstractMesh(name, scene) {
  19501. if (scene === void 0) { scene = null; }
  19502. var _this = _super.call(this, name, scene, false) || this;
  19503. _this._facetNb = 0; // facet number
  19504. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19505. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19506. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19507. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19508. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19509. _this._subDiv = {
  19510. max: 1,
  19511. X: 1,
  19512. Y: 1,
  19513. Z: 1
  19514. };
  19515. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19516. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19517. /** Gets ot sets the culling strategy to use to find visible meshes */
  19518. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19519. // Events
  19520. /**
  19521. * An event triggered when this mesh collides with another one
  19522. */
  19523. _this.onCollideObservable = new BABYLON.Observable();
  19524. /**
  19525. * An event triggered when the collision's position changes
  19526. */
  19527. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19528. /**
  19529. * An event triggered when material is changed
  19530. */
  19531. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19532. // Properties
  19533. /**
  19534. * Gets or sets the orientation for POV movement & rotation
  19535. */
  19536. _this.definedFacingForward = true;
  19537. /**
  19538. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19539. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19540. * * 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.
  19541. * @see http://doc.babylonjs.com/features/occlusionquery
  19542. */
  19543. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19544. /**
  19545. * 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:
  19546. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19547. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19548. * * 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.
  19549. * @see http://doc.babylonjs.com/features/occlusionquery
  19550. */
  19551. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19552. /**
  19553. * 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.
  19554. * The default value is -1 which means don't break the query and wait till the result
  19555. * @see http://doc.babylonjs.com/features/occlusionquery
  19556. */
  19557. _this.occlusionRetryCount = -1;
  19558. /** @hidden */
  19559. _this._occlusionInternalRetryCounter = 0;
  19560. /** @hidden */
  19561. _this._isOccluded = false;
  19562. /** @hidden */
  19563. _this._isOcclusionQueryInProgress = false;
  19564. _this._visibility = 1.0;
  19565. /** Gets or sets the alpha index used to sort transparent meshes
  19566. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19567. */
  19568. _this.alphaIndex = Number.MAX_VALUE;
  19569. /**
  19570. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19571. */
  19572. _this.isVisible = true;
  19573. /**
  19574. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19575. */
  19576. _this.isPickable = true;
  19577. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19578. _this.showSubMeshesBoundingBox = false;
  19579. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19580. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19581. */
  19582. _this.isBlocker = false;
  19583. /**
  19584. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19585. */
  19586. _this.enablePointerMoveEvents = false;
  19587. /**
  19588. * Specifies the rendering group id for this mesh (0 by default)
  19589. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19590. */
  19591. _this.renderingGroupId = 0;
  19592. _this._receiveShadows = false;
  19593. /** Defines color to use when rendering outline */
  19594. _this.outlineColor = BABYLON.Color3.Red();
  19595. /** Define width to use when rendering outline */
  19596. _this.outlineWidth = 0.02;
  19597. /** Defines color to use when rendering overlay */
  19598. _this.overlayColor = BABYLON.Color3.Red();
  19599. /** Defines alpha to use when rendering overlay */
  19600. _this.overlayAlpha = 0.5;
  19601. _this._hasVertexAlpha = false;
  19602. _this._useVertexColors = true;
  19603. _this._computeBonesUsingShaders = true;
  19604. _this._numBoneInfluencers = 4;
  19605. _this._applyFog = true;
  19606. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19607. _this.useOctreeForRenderingSelection = true;
  19608. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19609. _this.useOctreeForPicking = true;
  19610. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19611. _this.useOctreeForCollisions = true;
  19612. _this._layerMask = 0x0FFFFFFF;
  19613. /**
  19614. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19615. */
  19616. _this.alwaysSelectAsActiveMesh = false;
  19617. /**
  19618. * Gets or sets the current action manager
  19619. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19620. */
  19621. _this.actionManager = null;
  19622. /**
  19623. * Gets or sets impostor used for physic simulation
  19624. * @see http://doc.babylonjs.com/features/physics_engine
  19625. */
  19626. _this.physicsImpostor = null;
  19627. // Collisions
  19628. _this._checkCollisions = false;
  19629. _this._collisionMask = -1;
  19630. _this._collisionGroup = -1;
  19631. /**
  19632. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19633. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19634. */
  19635. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19636. /**
  19637. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19638. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19639. */
  19640. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19641. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19642. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19643. // Edges
  19644. /**
  19645. * Defines edge width used when edgesRenderer is enabled
  19646. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19647. */
  19648. _this.edgesWidth = 1;
  19649. /**
  19650. * Defines edge color used when edgesRenderer is enabled
  19651. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19652. */
  19653. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19654. // Cache
  19655. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19656. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19657. /** @hidden */
  19658. _this._renderId = 0;
  19659. /** @hidden */
  19660. _this._intersectionsInProgress = new Array();
  19661. /** @hidden */
  19662. _this._unIndexed = false;
  19663. /** @hidden */
  19664. _this._lightSources = new Array();
  19665. /**
  19666. * An event triggered when the mesh is rebuilt.
  19667. */
  19668. _this.onRebuildObservable = new BABYLON.Observable();
  19669. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19670. if (collidedMesh === void 0) { collidedMesh = null; }
  19671. //TODO move this to the collision coordinator!
  19672. if (_this.getScene().workerCollisions)
  19673. newPosition.multiplyInPlace(_this._collider._radius);
  19674. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19675. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19676. _this.position.addInPlace(_this._diffPositionForCollisions);
  19677. }
  19678. if (collidedMesh) {
  19679. _this.onCollideObservable.notifyObservers(collidedMesh);
  19680. }
  19681. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19682. };
  19683. _this.getScene().addMesh(_this);
  19684. _this._resyncLightSources();
  19685. return _this;
  19686. }
  19687. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19688. /**
  19689. * No billboard
  19690. */
  19691. get: function () {
  19692. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19698. /** Billboard on X axis */
  19699. get: function () {
  19700. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19706. /** Billboard on Y axis */
  19707. get: function () {
  19708. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19714. /** Billboard on Z axis */
  19715. get: function () {
  19716. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19722. /** Billboard on all axes */
  19723. get: function () {
  19724. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19730. /**
  19731. * Gets the number of facets in the mesh
  19732. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19733. */
  19734. get: function () {
  19735. return this._facetNb;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19741. /**
  19742. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19743. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19744. */
  19745. get: function () {
  19746. return this._partitioningSubdivisions;
  19747. },
  19748. set: function (nb) {
  19749. this._partitioningSubdivisions = nb;
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19755. /**
  19756. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19757. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19758. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19759. */
  19760. get: function () {
  19761. return this._partitioningBBoxRatio;
  19762. },
  19763. set: function (ratio) {
  19764. this._partitioningBBoxRatio = ratio;
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19770. /**
  19771. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19772. * Works only for updatable meshes.
  19773. * Doesn't work with multi-materials
  19774. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19775. */
  19776. get: function () {
  19777. return this._facetDepthSort;
  19778. },
  19779. set: function (sort) {
  19780. this._facetDepthSort = sort;
  19781. },
  19782. enumerable: true,
  19783. configurable: true
  19784. });
  19785. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19786. /**
  19787. * The location (Vector3) where the facet depth sort must be computed from.
  19788. * By default, the active camera position.
  19789. * Used only when facet depth sort is enabled
  19790. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19791. */
  19792. get: function () {
  19793. return this._facetDepthSortFrom;
  19794. },
  19795. set: function (location) {
  19796. this._facetDepthSortFrom = location;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19802. /**
  19803. * gets a boolean indicating if facetData is enabled
  19804. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19805. */
  19806. get: function () {
  19807. return this._facetDataEnabled;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. /** @hidden */
  19813. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19814. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19815. return false;
  19816. }
  19817. this._markSubMeshesAsMiscDirty();
  19818. return true;
  19819. };
  19820. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19821. /** Set a function to call when this mesh collides with another one */
  19822. set: function (callback) {
  19823. if (this._onCollideObserver) {
  19824. this.onCollideObservable.remove(this._onCollideObserver);
  19825. }
  19826. this._onCollideObserver = this.onCollideObservable.add(callback);
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19832. /** Set a function to call when the collision's position changes */
  19833. set: function (callback) {
  19834. if (this._onCollisionPositionChangeObserver) {
  19835. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19836. }
  19837. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19843. /**
  19844. * 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
  19845. * @see http://doc.babylonjs.com/features/occlusionquery
  19846. */
  19847. get: function () {
  19848. return this._isOccluded;
  19849. },
  19850. set: function (value) {
  19851. this._isOccluded = value;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19857. /**
  19858. * Flag to check the progress status of the query
  19859. * @see http://doc.babylonjs.com/features/occlusionquery
  19860. */
  19861. get: function () {
  19862. return this._isOcclusionQueryInProgress;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19868. /**
  19869. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19870. */
  19871. get: function () {
  19872. return this._visibility;
  19873. },
  19874. /**
  19875. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19876. */
  19877. set: function (value) {
  19878. if (this._visibility === value) {
  19879. return;
  19880. }
  19881. this._visibility = value;
  19882. this._markSubMeshesAsMiscDirty();
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(AbstractMesh.prototype, "material", {
  19888. /** Gets or sets current material */
  19889. get: function () {
  19890. return this._material;
  19891. },
  19892. set: function (value) {
  19893. if (this._material === value) {
  19894. return;
  19895. }
  19896. this._material = value;
  19897. if (this.onMaterialChangedObservable.hasObservers) {
  19898. this.onMaterialChangedObservable.notifyObservers(this);
  19899. }
  19900. if (!this.subMeshes) {
  19901. return;
  19902. }
  19903. this._unBindEffect();
  19904. },
  19905. enumerable: true,
  19906. configurable: true
  19907. });
  19908. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19909. /**
  19910. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19911. * @see http://doc.babylonjs.com/babylon101/shadows
  19912. */
  19913. get: function () {
  19914. return this._receiveShadows;
  19915. },
  19916. set: function (value) {
  19917. if (this._receiveShadows === value) {
  19918. return;
  19919. }
  19920. this._receiveShadows = value;
  19921. this._markSubMeshesAsLightDirty();
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19927. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19928. get: function () {
  19929. return this._hasVertexAlpha;
  19930. },
  19931. set: function (value) {
  19932. if (this._hasVertexAlpha === value) {
  19933. return;
  19934. }
  19935. this._hasVertexAlpha = value;
  19936. this._markSubMeshesAsAttributesDirty();
  19937. this._markSubMeshesAsMiscDirty();
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19943. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19944. get: function () {
  19945. return this._useVertexColors;
  19946. },
  19947. set: function (value) {
  19948. if (this._useVertexColors === value) {
  19949. return;
  19950. }
  19951. this._useVertexColors = value;
  19952. this._markSubMeshesAsAttributesDirty();
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19958. /**
  19959. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19960. */
  19961. get: function () {
  19962. return this._computeBonesUsingShaders;
  19963. },
  19964. set: function (value) {
  19965. if (this._computeBonesUsingShaders === value) {
  19966. return;
  19967. }
  19968. this._computeBonesUsingShaders = value;
  19969. this._markSubMeshesAsAttributesDirty();
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19975. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19976. get: function () {
  19977. return this._numBoneInfluencers;
  19978. },
  19979. set: function (value) {
  19980. if (this._numBoneInfluencers === value) {
  19981. return;
  19982. }
  19983. this._numBoneInfluencers = value;
  19984. this._markSubMeshesAsAttributesDirty();
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19990. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19991. get: function () {
  19992. return this._applyFog;
  19993. },
  19994. set: function (value) {
  19995. if (this._applyFog === value) {
  19996. return;
  19997. }
  19998. this._applyFog = value;
  19999. this._markSubMeshesAsMiscDirty();
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20005. /**
  20006. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20007. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20008. */
  20009. get: function () {
  20010. return this._layerMask;
  20011. },
  20012. set: function (value) {
  20013. if (value === this._layerMask) {
  20014. return;
  20015. }
  20016. this._layerMask = value;
  20017. this._resyncLightSources();
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20023. /**
  20024. * Gets or sets a collision mask used to mask collisions (default is -1).
  20025. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20026. */
  20027. get: function () {
  20028. return this._collisionMask;
  20029. },
  20030. set: function (mask) {
  20031. this._collisionMask = !isNaN(mask) ? mask : -1;
  20032. },
  20033. enumerable: true,
  20034. configurable: true
  20035. });
  20036. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20037. /**
  20038. * Gets or sets the current collision group mask (-1 by default).
  20039. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20040. */
  20041. get: function () {
  20042. return this._collisionGroup;
  20043. },
  20044. set: function (mask) {
  20045. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20051. /** @hidden */
  20052. get: function () {
  20053. return null;
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20059. get: function () {
  20060. return this._skeleton;
  20061. },
  20062. /**
  20063. * Gets or sets a skeleton to apply skining transformations
  20064. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20065. */
  20066. set: function (value) {
  20067. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20068. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20069. }
  20070. if (value && value.needInitialSkinMatrix) {
  20071. value._registerMeshWithPoseMatrix(this);
  20072. }
  20073. this._skeleton = value;
  20074. if (!this._skeleton) {
  20075. this._bonesTransformMatrices = null;
  20076. }
  20077. this._markSubMeshesAsAttributesDirty();
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. /**
  20083. * Returns the string "AbstractMesh"
  20084. * @returns "AbstractMesh"
  20085. */
  20086. AbstractMesh.prototype.getClassName = function () {
  20087. return "AbstractMesh";
  20088. };
  20089. /**
  20090. * Gets a string representation of the current mesh
  20091. * @param fullDetails defines a boolean indicating if full details must be included
  20092. * @returns a string representation of the current mesh
  20093. */
  20094. AbstractMesh.prototype.toString = function (fullDetails) {
  20095. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20096. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20097. if (this._skeleton) {
  20098. ret += ", skeleton: " + this._skeleton.name;
  20099. }
  20100. if (fullDetails) {
  20101. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20102. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20103. }
  20104. return ret;
  20105. };
  20106. /** @hidden */
  20107. AbstractMesh.prototype._rebuild = function () {
  20108. this.onRebuildObservable.notifyObservers(this);
  20109. if (this._occlusionQuery) {
  20110. this._occlusionQuery = null;
  20111. }
  20112. if (!this.subMeshes) {
  20113. return;
  20114. }
  20115. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20116. var subMesh = _a[_i];
  20117. subMesh._rebuild();
  20118. }
  20119. };
  20120. /** @hidden */
  20121. AbstractMesh.prototype._resyncLightSources = function () {
  20122. this._lightSources.length = 0;
  20123. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20124. var light = _a[_i];
  20125. if (!light.isEnabled()) {
  20126. continue;
  20127. }
  20128. if (light.canAffectMesh(this)) {
  20129. this._lightSources.push(light);
  20130. }
  20131. }
  20132. this._markSubMeshesAsLightDirty();
  20133. };
  20134. /** @hidden */
  20135. AbstractMesh.prototype._resyncLighSource = function (light) {
  20136. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20137. var index = this._lightSources.indexOf(light);
  20138. if (index === -1) {
  20139. if (!isIn) {
  20140. return;
  20141. }
  20142. this._lightSources.push(light);
  20143. }
  20144. else {
  20145. if (isIn) {
  20146. return;
  20147. }
  20148. this._lightSources.splice(index, 1);
  20149. }
  20150. this._markSubMeshesAsLightDirty();
  20151. };
  20152. /** @hidden */
  20153. AbstractMesh.prototype._unBindEffect = function () {
  20154. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20155. var subMesh = _a[_i];
  20156. subMesh.setEffect(null);
  20157. }
  20158. };
  20159. /** @hidden */
  20160. AbstractMesh.prototype._removeLightSource = function (light) {
  20161. var index = this._lightSources.indexOf(light);
  20162. if (index === -1) {
  20163. return;
  20164. }
  20165. this._lightSources.splice(index, 1);
  20166. this._markSubMeshesAsLightDirty();
  20167. };
  20168. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20169. if (!this.subMeshes) {
  20170. return;
  20171. }
  20172. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20173. var subMesh = _a[_i];
  20174. if (subMesh._materialDefines) {
  20175. func(subMesh._materialDefines);
  20176. }
  20177. }
  20178. };
  20179. /** @hidden */
  20180. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20181. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20182. };
  20183. /** @hidden */
  20184. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20185. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20186. };
  20187. /** @hidden */
  20188. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20189. if (!this.subMeshes) {
  20190. return;
  20191. }
  20192. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20193. var subMesh = _a[_i];
  20194. var material = subMesh.getMaterial();
  20195. if (material) {
  20196. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20197. }
  20198. }
  20199. };
  20200. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20201. /**
  20202. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20203. */
  20204. get: function () {
  20205. return this._scaling;
  20206. },
  20207. set: function (newScaling) {
  20208. this._scaling = newScaling;
  20209. if (this.physicsImpostor) {
  20210. this.physicsImpostor.forceUpdate();
  20211. }
  20212. },
  20213. enumerable: true,
  20214. configurable: true
  20215. });
  20216. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20217. // Methods
  20218. /**
  20219. * Returns true if the mesh is blocked. Implemented by child classes
  20220. */
  20221. get: function () {
  20222. return false;
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. /**
  20228. * Returns the mesh itself by default. Implemented by child classes
  20229. * @param camera defines the camera to use to pick the right LOD level
  20230. * @returns the currentAbstractMesh
  20231. */
  20232. AbstractMesh.prototype.getLOD = function (camera) {
  20233. return this;
  20234. };
  20235. /**
  20236. * Returns 0 by default. Implemented by child classes
  20237. * @returns an integer
  20238. */
  20239. AbstractMesh.prototype.getTotalVertices = function () {
  20240. return 0;
  20241. };
  20242. /**
  20243. * Returns null by default. Implemented by child classes
  20244. * @returns null
  20245. */
  20246. AbstractMesh.prototype.getIndices = function () {
  20247. return null;
  20248. };
  20249. /**
  20250. * Returns the array of the requested vertex data kind. Implemented by child classes
  20251. * @param kind defines the vertex data kind to use
  20252. * @returns null
  20253. */
  20254. AbstractMesh.prototype.getVerticesData = function (kind) {
  20255. return null;
  20256. };
  20257. /**
  20258. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20259. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20260. * Note that a new underlying VertexBuffer object is created each call.
  20261. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20262. * @param kind defines vertex data kind:
  20263. * * BABYLON.VertexBuffer.PositionKind
  20264. * * BABYLON.VertexBuffer.UVKind
  20265. * * BABYLON.VertexBuffer.UV2Kind
  20266. * * BABYLON.VertexBuffer.UV3Kind
  20267. * * BABYLON.VertexBuffer.UV4Kind
  20268. * * BABYLON.VertexBuffer.UV5Kind
  20269. * * BABYLON.VertexBuffer.UV6Kind
  20270. * * BABYLON.VertexBuffer.ColorKind
  20271. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20272. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20273. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20274. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20275. * @param data defines the data source
  20276. * @param updatable defines if the data must be flagged as updatable (or static)
  20277. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20278. * @returns the current mesh
  20279. */
  20280. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20281. return this;
  20282. };
  20283. /**
  20284. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20285. * If the mesh has no geometry, it is simply returned as it is.
  20286. * @param kind defines vertex data kind:
  20287. * * BABYLON.VertexBuffer.PositionKind
  20288. * * BABYLON.VertexBuffer.UVKind
  20289. * * BABYLON.VertexBuffer.UV2Kind
  20290. * * BABYLON.VertexBuffer.UV3Kind
  20291. * * BABYLON.VertexBuffer.UV4Kind
  20292. * * BABYLON.VertexBuffer.UV5Kind
  20293. * * BABYLON.VertexBuffer.UV6Kind
  20294. * * BABYLON.VertexBuffer.ColorKind
  20295. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20296. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20297. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20298. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20299. * @param data defines the data source
  20300. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20301. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20302. * @returns the current mesh
  20303. */
  20304. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20305. return this;
  20306. };
  20307. /**
  20308. * Sets the mesh indices,
  20309. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20310. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20311. * @param totalVertices Defines the total number of vertices
  20312. * @returns the current mesh
  20313. */
  20314. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20315. return this;
  20316. };
  20317. /**
  20318. * Gets a boolean indicating if specific vertex data is present
  20319. * @param kind defines the vertex data kind to use
  20320. * @returns true is data kind is present
  20321. */
  20322. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20323. return false;
  20324. };
  20325. /**
  20326. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20327. * @returns a BoundingInfo
  20328. */
  20329. AbstractMesh.prototype.getBoundingInfo = function () {
  20330. if (this._masterMesh) {
  20331. return this._masterMesh.getBoundingInfo();
  20332. }
  20333. if (!this._boundingInfo) {
  20334. // this._boundingInfo is being created here
  20335. this._updateBoundingInfo();
  20336. }
  20337. // cannot be null.
  20338. return this._boundingInfo;
  20339. };
  20340. /**
  20341. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20342. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20343. * @returns the current mesh
  20344. */
  20345. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20346. if (includeDescendants === void 0) { includeDescendants = true; }
  20347. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20348. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20349. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20350. if (maxDimension === 0) {
  20351. return this;
  20352. }
  20353. var scale = 1 / maxDimension;
  20354. this.scaling.scaleInPlace(scale);
  20355. return this;
  20356. };
  20357. /**
  20358. * Overwrite the current bounding info
  20359. * @param boundingInfo defines the new bounding info
  20360. * @returns the current mesh
  20361. */
  20362. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20363. this._boundingInfo = boundingInfo;
  20364. return this;
  20365. };
  20366. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20367. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20368. get: function () {
  20369. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20370. },
  20371. enumerable: true,
  20372. configurable: true
  20373. });
  20374. /** @hidden */
  20375. AbstractMesh.prototype._preActivate = function () {
  20376. };
  20377. /** @hidden */
  20378. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20379. };
  20380. /** @hidden */
  20381. AbstractMesh.prototype._activate = function (renderId) {
  20382. this._renderId = renderId;
  20383. };
  20384. /**
  20385. * Gets the current world matrix
  20386. * @returns a Matrix
  20387. */
  20388. AbstractMesh.prototype.getWorldMatrix = function () {
  20389. if (this._masterMesh) {
  20390. return this._masterMesh.getWorldMatrix();
  20391. }
  20392. return _super.prototype.getWorldMatrix.call(this);
  20393. };
  20394. /** @hidden */
  20395. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20396. if (this._masterMesh) {
  20397. return this._masterMesh._getWorldMatrixDeterminant();
  20398. }
  20399. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20400. };
  20401. // ================================== Point of View Movement =================================
  20402. /**
  20403. * Perform relative position change from the point of view of behind the front of the mesh.
  20404. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20405. * Supports definition of mesh facing forward or backward
  20406. * @param amountRight defines the distance on the right axis
  20407. * @param amountUp defines the distance on the up axis
  20408. * @param amountForward defines the distance on the forward axis
  20409. * @returns the current mesh
  20410. */
  20411. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20412. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20413. return this;
  20414. };
  20415. /**
  20416. * Calculate relative position change from the point of view of behind the front of the mesh.
  20417. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20418. * Supports definition of mesh facing forward or backward
  20419. * @param amountRight defines the distance on the right axis
  20420. * @param amountUp defines the distance on the up axis
  20421. * @param amountForward defines the distance on the forward axis
  20422. * @returns the new displacement vector
  20423. */
  20424. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20425. var rotMatrix = new BABYLON.Matrix();
  20426. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20427. rotQuaternion.toRotationMatrix(rotMatrix);
  20428. var translationDelta = BABYLON.Vector3.Zero();
  20429. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20430. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20431. return translationDelta;
  20432. };
  20433. // ================================== Point of View Rotation =================================
  20434. /**
  20435. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20436. * Supports definition of mesh facing forward or backward
  20437. * @param flipBack defines the flip
  20438. * @param twirlClockwise defines the twirl
  20439. * @param tiltRight defines the tilt
  20440. * @returns the current mesh
  20441. */
  20442. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20443. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20444. return this;
  20445. };
  20446. /**
  20447. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20448. * Supports definition of mesh facing forward or backward.
  20449. * @param flipBack defines the flip
  20450. * @param twirlClockwise defines the twirl
  20451. * @param tiltRight defines the tilt
  20452. * @returns the new rotation vector
  20453. */
  20454. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20455. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20456. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20457. };
  20458. /**
  20459. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20460. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20461. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20462. * @returns the new bounding vectors
  20463. */
  20464. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20465. if (includeDescendants === void 0) { includeDescendants = true; }
  20466. if (predicate === void 0) { predicate = null; }
  20467. // Ensures that all world matrix will be recomputed.
  20468. this.getScene().incrementRenderId();
  20469. this.computeWorldMatrix(true);
  20470. var min;
  20471. var max;
  20472. var boundingInfo = this.getBoundingInfo();
  20473. if (!this.subMeshes) {
  20474. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20475. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20476. }
  20477. else {
  20478. min = boundingInfo.boundingBox.minimumWorld;
  20479. max = boundingInfo.boundingBox.maximumWorld;
  20480. }
  20481. if (includeDescendants) {
  20482. var descendants = this.getDescendants(false);
  20483. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20484. var descendant = descendants_1[_i];
  20485. var childMesh = descendant;
  20486. childMesh.computeWorldMatrix(true);
  20487. // Filters meshes based on custom predicate function.
  20488. if (predicate && !predicate(childMesh)) {
  20489. continue;
  20490. }
  20491. //make sure we have the needed params to get mix and max
  20492. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20493. continue;
  20494. }
  20495. var childBoundingInfo = childMesh.getBoundingInfo();
  20496. var boundingBox = childBoundingInfo.boundingBox;
  20497. var minBox = boundingBox.minimumWorld;
  20498. var maxBox = boundingBox.maximumWorld;
  20499. BABYLON.Tools.CheckExtends(minBox, min, max);
  20500. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20501. }
  20502. }
  20503. return {
  20504. min: min,
  20505. max: max
  20506. };
  20507. };
  20508. /** @hidden */
  20509. AbstractMesh.prototype._updateBoundingInfo = function () {
  20510. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20511. this._boundingInfo.update(this.worldMatrixFromCache);
  20512. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20513. return this;
  20514. };
  20515. /** @hidden */
  20516. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20517. if (!this.subMeshes) {
  20518. return this;
  20519. }
  20520. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20521. var subMesh = this.subMeshes[subIndex];
  20522. if (!subMesh.IsGlobal) {
  20523. subMesh.updateBoundingInfo(matrix);
  20524. }
  20525. }
  20526. return this;
  20527. };
  20528. /** @hidden */
  20529. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20530. // Bounding info
  20531. this._updateBoundingInfo();
  20532. };
  20533. /**
  20534. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20535. * A mesh is in the frustum if its bounding box intersects the frustum
  20536. * @param frustumPlanes defines the frustum to test
  20537. * @returns true if the mesh is in the frustum planes
  20538. */
  20539. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20540. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20541. };
  20542. /**
  20543. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20544. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20545. * @param frustumPlanes defines the frustum to test
  20546. * @returns true if the mesh is completely in the frustum planes
  20547. */
  20548. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20549. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20550. };
  20551. /**
  20552. * True if the mesh intersects another mesh or a SolidParticle object
  20553. * @param mesh defines a target mesh or SolidParticle to test
  20554. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20555. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20556. * @returns true if there is an intersection
  20557. */
  20558. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20559. if (precise === void 0) { precise = false; }
  20560. if (!this._boundingInfo || !mesh._boundingInfo) {
  20561. return false;
  20562. }
  20563. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20564. return true;
  20565. }
  20566. if (includeDescendants) {
  20567. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20568. var child = _a[_i];
  20569. if (child.intersectsMesh(mesh, precise, true)) {
  20570. return true;
  20571. }
  20572. }
  20573. }
  20574. return false;
  20575. };
  20576. /**
  20577. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20578. * @param point defines the point to test
  20579. * @returns true if there is an intersection
  20580. */
  20581. AbstractMesh.prototype.intersectsPoint = function (point) {
  20582. if (!this._boundingInfo) {
  20583. return false;
  20584. }
  20585. return this._boundingInfo.intersectsPoint(point);
  20586. };
  20587. /**
  20588. * Gets the current physics impostor
  20589. * @see http://doc.babylonjs.com/features/physics_engine
  20590. * @returns a physics impostor or null
  20591. */
  20592. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20593. return this.physicsImpostor;
  20594. };
  20595. /**
  20596. * Gets the position of the current mesh in camera space
  20597. * @param camera defines the camera to use
  20598. * @returns a position
  20599. */
  20600. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20601. if (camera === void 0) { camera = null; }
  20602. if (!camera) {
  20603. camera = this.getScene().activeCamera;
  20604. }
  20605. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20606. };
  20607. /**
  20608. * Returns the distance from the mesh to the active camera
  20609. * @param camera defines the camera to use
  20610. * @returns the distance
  20611. */
  20612. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20613. if (camera === void 0) { camera = null; }
  20614. if (!camera) {
  20615. camera = this.getScene().activeCamera;
  20616. }
  20617. return this.absolutePosition.subtract(camera.position).length();
  20618. };
  20619. /**
  20620. * Apply a physic impulse to the mesh
  20621. * @param force defines the force to apply
  20622. * @param contactPoint defines where to apply the force
  20623. * @returns the current mesh
  20624. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20625. */
  20626. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20627. if (!this.physicsImpostor) {
  20628. return this;
  20629. }
  20630. this.physicsImpostor.applyImpulse(force, contactPoint);
  20631. return this;
  20632. };
  20633. /**
  20634. * Creates a physic joint between two meshes
  20635. * @param otherMesh defines the other mesh to use
  20636. * @param pivot1 defines the pivot to use on this mesh
  20637. * @param pivot2 defines the pivot to use on the other mesh
  20638. * @param options defines additional options (can be plugin dependent)
  20639. * @returns the current mesh
  20640. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20641. */
  20642. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20643. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20644. return this;
  20645. }
  20646. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20647. mainPivot: pivot1,
  20648. connectedPivot: pivot2,
  20649. nativeParams: options
  20650. });
  20651. return this;
  20652. };
  20653. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20654. // Collisions
  20655. /**
  20656. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20657. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20658. */
  20659. get: function () {
  20660. return this._checkCollisions;
  20661. },
  20662. set: function (collisionEnabled) {
  20663. this._checkCollisions = collisionEnabled;
  20664. if (this.getScene().workerCollisions) {
  20665. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20666. }
  20667. },
  20668. enumerable: true,
  20669. configurable: true
  20670. });
  20671. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20672. /**
  20673. * Gets Collider object used to compute collisions (not physics)
  20674. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20675. */
  20676. get: function () {
  20677. return this._collider;
  20678. },
  20679. enumerable: true,
  20680. configurable: true
  20681. });
  20682. /**
  20683. * Move the mesh using collision engine
  20684. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20685. * @param displacement defines the requested displacement vector
  20686. * @returns the current mesh
  20687. */
  20688. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20689. var globalPosition = this.getAbsolutePosition();
  20690. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20691. if (!this._collider) {
  20692. this._collider = new BABYLON.Collider();
  20693. }
  20694. this._collider._radius = this.ellipsoid;
  20695. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20696. return this;
  20697. };
  20698. // Submeshes octree
  20699. /**
  20700. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20701. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20702. * @param maxCapacity defines the maximum size of each block (64 by default)
  20703. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20704. * @returns the new octree
  20705. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20706. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20707. */
  20708. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20709. if (maxCapacity === void 0) { maxCapacity = 64; }
  20710. if (maxDepth === void 0) { maxDepth = 2; }
  20711. if (!this._submeshesOctree) {
  20712. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20713. }
  20714. this.computeWorldMatrix(true);
  20715. var boundingInfo = this.getBoundingInfo();
  20716. // Update octree
  20717. var bbox = boundingInfo.boundingBox;
  20718. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20719. return this._submeshesOctree;
  20720. };
  20721. // Collisions
  20722. /** @hidden */
  20723. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20724. this._generatePointsArray();
  20725. if (!this._positions) {
  20726. return this;
  20727. }
  20728. // Transformation
  20729. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20730. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20731. subMesh._lastColliderWorldVertices = [];
  20732. subMesh._trianglePlanes = [];
  20733. var start = subMesh.verticesStart;
  20734. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20735. for (var i = start; i < end; i++) {
  20736. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20737. }
  20738. }
  20739. // Collide
  20740. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20741. if (collider.collisionFound) {
  20742. collider.collidedMesh = this;
  20743. }
  20744. return this;
  20745. };
  20746. /** @hidden */
  20747. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20748. var subMeshes;
  20749. var len;
  20750. // Octrees
  20751. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20752. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20753. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20754. len = intersections.length;
  20755. subMeshes = intersections.data;
  20756. }
  20757. else {
  20758. subMeshes = this.subMeshes;
  20759. len = subMeshes.length;
  20760. }
  20761. for (var index = 0; index < len; index++) {
  20762. var subMesh = subMeshes[index];
  20763. // Bounding test
  20764. if (len > 1 && !subMesh._checkCollision(collider))
  20765. continue;
  20766. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20767. }
  20768. return this;
  20769. };
  20770. /** @hidden */
  20771. AbstractMesh.prototype._checkCollision = function (collider) {
  20772. // Bounding box test
  20773. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20774. return this;
  20775. // Transformation matrix
  20776. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20777. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20778. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20779. return this;
  20780. };
  20781. // Picking
  20782. /** @hidden */
  20783. AbstractMesh.prototype._generatePointsArray = function () {
  20784. return false;
  20785. };
  20786. /**
  20787. * Checks if the passed Ray intersects with the mesh
  20788. * @param ray defines the ray to use
  20789. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20790. * @returns the picking info
  20791. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20792. */
  20793. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20794. var pickingInfo = new BABYLON.PickingInfo();
  20795. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20796. return pickingInfo;
  20797. }
  20798. if (!this._generatePointsArray()) {
  20799. return pickingInfo;
  20800. }
  20801. var intersectInfo = null;
  20802. // Octrees
  20803. var subMeshes;
  20804. var len;
  20805. if (this._submeshesOctree && this.useOctreeForPicking) {
  20806. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20807. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20808. len = intersections.length;
  20809. subMeshes = intersections.data;
  20810. }
  20811. else {
  20812. subMeshes = this.subMeshes;
  20813. len = subMeshes.length;
  20814. }
  20815. for (var index = 0; index < len; index++) {
  20816. var subMesh = subMeshes[index];
  20817. // Bounding test
  20818. if (len > 1 && !subMesh.canIntersects(ray))
  20819. continue;
  20820. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20821. if (currentIntersectInfo) {
  20822. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20823. intersectInfo = currentIntersectInfo;
  20824. intersectInfo.subMeshId = index;
  20825. if (fastCheck) {
  20826. break;
  20827. }
  20828. }
  20829. }
  20830. }
  20831. if (intersectInfo) {
  20832. // Get picked point
  20833. var world = this.getWorldMatrix();
  20834. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20835. var direction = ray.direction.clone();
  20836. direction = direction.scale(intersectInfo.distance);
  20837. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20838. var pickedPoint = worldOrigin.add(worldDirection);
  20839. // Return result
  20840. pickingInfo.hit = true;
  20841. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20842. pickingInfo.pickedPoint = pickedPoint;
  20843. pickingInfo.pickedMesh = this;
  20844. pickingInfo.bu = intersectInfo.bu || 0;
  20845. pickingInfo.bv = intersectInfo.bv || 0;
  20846. pickingInfo.faceId = intersectInfo.faceId;
  20847. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20848. return pickingInfo;
  20849. }
  20850. return pickingInfo;
  20851. };
  20852. /**
  20853. * Clones the current mesh
  20854. * @param name defines the mesh name
  20855. * @param newParent defines the new mesh parent
  20856. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20857. * @returns the new mesh
  20858. */
  20859. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20860. return null;
  20861. };
  20862. /**
  20863. * Disposes all the submeshes of the current meshnp
  20864. * @returns the current mesh
  20865. */
  20866. AbstractMesh.prototype.releaseSubMeshes = function () {
  20867. if (this.subMeshes) {
  20868. while (this.subMeshes.length) {
  20869. this.subMeshes[0].dispose();
  20870. }
  20871. }
  20872. else {
  20873. this.subMeshes = new Array();
  20874. }
  20875. return this;
  20876. };
  20877. /**
  20878. * Releases resources associated with this abstract mesh.
  20879. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20880. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20881. */
  20882. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20883. var _this = this;
  20884. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20885. var index;
  20886. // Smart Array Retainers.
  20887. this.getScene().freeActiveMeshes();
  20888. this.getScene().freeRenderingGroups();
  20889. // Action manager
  20890. if (this.actionManager !== undefined && this.actionManager !== null) {
  20891. this.actionManager.dispose();
  20892. this.actionManager = null;
  20893. }
  20894. // Skeleton
  20895. this._skeleton = null;
  20896. // Physics
  20897. if (this.physicsImpostor) {
  20898. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20899. }
  20900. // Intersections in progress
  20901. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20902. var other = this._intersectionsInProgress[index];
  20903. var pos = other._intersectionsInProgress.indexOf(this);
  20904. other._intersectionsInProgress.splice(pos, 1);
  20905. }
  20906. this._intersectionsInProgress = [];
  20907. // Lights
  20908. var lights = this.getScene().lights;
  20909. lights.forEach(function (light) {
  20910. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20911. if (meshIndex !== -1) {
  20912. light.includedOnlyMeshes.splice(meshIndex, 1);
  20913. }
  20914. meshIndex = light.excludedMeshes.indexOf(_this);
  20915. if (meshIndex !== -1) {
  20916. light.excludedMeshes.splice(meshIndex, 1);
  20917. }
  20918. // Shadow generators
  20919. var generator = light.getShadowGenerator();
  20920. if (generator) {
  20921. var shadowMap = generator.getShadowMap();
  20922. if (shadowMap && shadowMap.renderList) {
  20923. meshIndex = shadowMap.renderList.indexOf(_this);
  20924. if (meshIndex !== -1) {
  20925. shadowMap.renderList.splice(meshIndex, 1);
  20926. }
  20927. }
  20928. }
  20929. });
  20930. // SubMeshes
  20931. if (this.getClassName() !== "InstancedMesh") {
  20932. this.releaseSubMeshes();
  20933. }
  20934. // Octree
  20935. var sceneOctree = this.getScene().selectionOctree;
  20936. if (sceneOctree !== undefined && sceneOctree !== null) {
  20937. var index = sceneOctree.dynamicContent.indexOf(this);
  20938. if (index !== -1) {
  20939. sceneOctree.dynamicContent.splice(index, 1);
  20940. }
  20941. }
  20942. // Query
  20943. var engine = this.getScene().getEngine();
  20944. if (this._occlusionQuery) {
  20945. this._isOcclusionQueryInProgress = false;
  20946. engine.deleteQuery(this._occlusionQuery);
  20947. this._occlusionQuery = null;
  20948. }
  20949. // Engine
  20950. engine.wipeCaches();
  20951. // Remove from scene
  20952. this.getScene().removeMesh(this);
  20953. if (disposeMaterialAndTextures) {
  20954. if (this.material) {
  20955. this.material.dispose(false, true);
  20956. }
  20957. }
  20958. if (!doNotRecurse) {
  20959. // Particles
  20960. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20961. if (this.getScene().particleSystems[index].emitter === this) {
  20962. this.getScene().particleSystems[index].dispose();
  20963. index--;
  20964. }
  20965. }
  20966. }
  20967. // facet data
  20968. if (this._facetDataEnabled) {
  20969. this.disableFacetData();
  20970. }
  20971. this.onAfterWorldMatrixUpdateObservable.clear();
  20972. this.onCollideObservable.clear();
  20973. this.onCollisionPositionChangeObservable.clear();
  20974. this.onRebuildObservable.clear();
  20975. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20976. };
  20977. /**
  20978. * Adds the passed mesh as a child to the current mesh
  20979. * @param mesh defines the child mesh
  20980. * @returns the current mesh
  20981. */
  20982. AbstractMesh.prototype.addChild = function (mesh) {
  20983. mesh.setParent(this);
  20984. return this;
  20985. };
  20986. /**
  20987. * Removes the passed mesh from the current mesh children list
  20988. * @param mesh defines the child mesh
  20989. * @returns the current mesh
  20990. */
  20991. AbstractMesh.prototype.removeChild = function (mesh) {
  20992. mesh.setParent(null);
  20993. return this;
  20994. };
  20995. // Facet data
  20996. /** @hidden */
  20997. AbstractMesh.prototype._initFacetData = function () {
  20998. if (!this._facetNormals) {
  20999. this._facetNormals = new Array();
  21000. }
  21001. if (!this._facetPositions) {
  21002. this._facetPositions = new Array();
  21003. }
  21004. if (!this._facetPartitioning) {
  21005. this._facetPartitioning = new Array();
  21006. }
  21007. this._facetNb = (this.getIndices().length / 3) | 0;
  21008. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21009. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21010. for (var f = 0; f < this._facetNb; f++) {
  21011. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21012. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21013. }
  21014. this._facetDataEnabled = true;
  21015. return this;
  21016. };
  21017. /**
  21018. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21019. * This method can be called within the render loop.
  21020. * 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
  21021. * @returns the current mesh
  21022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21023. */
  21024. AbstractMesh.prototype.updateFacetData = function () {
  21025. if (!this._facetDataEnabled) {
  21026. this._initFacetData();
  21027. }
  21028. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21029. var indices = this.getIndices();
  21030. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21031. var bInfo = this.getBoundingInfo();
  21032. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21033. // init arrays, matrix and sort function on first call
  21034. this._facetDepthSortEnabled = true;
  21035. if (indices instanceof Uint16Array) {
  21036. this._depthSortedIndices = new Uint16Array(indices);
  21037. }
  21038. else if (indices instanceof Uint32Array) {
  21039. this._depthSortedIndices = new Uint32Array(indices);
  21040. }
  21041. else {
  21042. var needs32bits = false;
  21043. for (var i = 0; i < indices.length; i++) {
  21044. if (indices[i] > 65535) {
  21045. needs32bits = true;
  21046. break;
  21047. }
  21048. }
  21049. if (needs32bits) {
  21050. this._depthSortedIndices = new Uint32Array(indices);
  21051. }
  21052. else {
  21053. this._depthSortedIndices = new Uint16Array(indices);
  21054. }
  21055. }
  21056. this._facetDepthSortFunction = function (f1, f2) {
  21057. return (f2.sqDistance - f1.sqDistance);
  21058. };
  21059. if (!this._facetDepthSortFrom) {
  21060. var camera = this.getScene().activeCamera;
  21061. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21062. }
  21063. this._depthSortedFacets = [];
  21064. for (var f = 0; f < this._facetNb; f++) {
  21065. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21066. this._depthSortedFacets.push(depthSortedFacet);
  21067. }
  21068. this._invertedMatrix = BABYLON.Matrix.Identity();
  21069. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21070. }
  21071. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21072. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21073. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21074. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21075. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21076. this._subDiv.max = this._partitioningSubdivisions;
  21077. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21078. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21079. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21080. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21081. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21082. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21083. // set the parameters for ComputeNormals()
  21084. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21085. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21086. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21087. this._facetParameters.bInfo = bInfo;
  21088. this._facetParameters.bbSize = this._bbSize;
  21089. this._facetParameters.subDiv = this._subDiv;
  21090. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21091. this._facetParameters.depthSort = this._facetDepthSort;
  21092. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21093. this.computeWorldMatrix(true);
  21094. this._worldMatrix.invertToRef(this._invertedMatrix);
  21095. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21096. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21097. }
  21098. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21099. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21100. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21101. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21102. var l = (this._depthSortedIndices.length / 3) | 0;
  21103. for (var f = 0; f < l; f++) {
  21104. var sind = this._depthSortedFacets[f].ind;
  21105. this._depthSortedIndices[f * 3] = indices[sind];
  21106. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21107. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21108. }
  21109. this.updateIndices(this._depthSortedIndices);
  21110. }
  21111. return this;
  21112. };
  21113. /**
  21114. * Returns the facetLocalNormals array.
  21115. * The normals are expressed in the mesh local spac
  21116. * @returns an array of Vector3
  21117. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21118. */
  21119. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21120. if (!this._facetNormals) {
  21121. this.updateFacetData();
  21122. }
  21123. return this._facetNormals;
  21124. };
  21125. /**
  21126. * Returns the facetLocalPositions array.
  21127. * The facet positions are expressed in the mesh local space
  21128. * @returns an array of Vector3
  21129. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21130. */
  21131. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21132. if (!this._facetPositions) {
  21133. this.updateFacetData();
  21134. }
  21135. return this._facetPositions;
  21136. };
  21137. /**
  21138. * Returns the facetLocalPartioning array
  21139. * @returns an array of array of numbers
  21140. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21141. */
  21142. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21143. if (!this._facetPartitioning) {
  21144. this.updateFacetData();
  21145. }
  21146. return this._facetPartitioning;
  21147. };
  21148. /**
  21149. * Returns the i-th facet position in the world system.
  21150. * This method allocates a new Vector3 per call
  21151. * @param i defines the facet index
  21152. * @returns a new Vector3
  21153. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21154. */
  21155. AbstractMesh.prototype.getFacetPosition = function (i) {
  21156. var pos = BABYLON.Vector3.Zero();
  21157. this.getFacetPositionToRef(i, pos);
  21158. return pos;
  21159. };
  21160. /**
  21161. * Sets the reference Vector3 with the i-th facet position in the world system
  21162. * @param i defines the facet index
  21163. * @param ref defines the target vector
  21164. * @returns the current mesh
  21165. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21166. */
  21167. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21168. var localPos = (this.getFacetLocalPositions())[i];
  21169. var world = this.getWorldMatrix();
  21170. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21171. return this;
  21172. };
  21173. /**
  21174. * Returns the i-th facet normal in the world system.
  21175. * This method allocates a new Vector3 per call
  21176. * @param i defines the facet index
  21177. * @returns a new Vector3
  21178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21179. */
  21180. AbstractMesh.prototype.getFacetNormal = function (i) {
  21181. var norm = BABYLON.Vector3.Zero();
  21182. this.getFacetNormalToRef(i, norm);
  21183. return norm;
  21184. };
  21185. /**
  21186. * Sets the reference Vector3 with the i-th facet normal in the world system
  21187. * @param i defines the facet index
  21188. * @param ref defines the target vector
  21189. * @returns the current mesh
  21190. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21191. */
  21192. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21193. var localNorm = (this.getFacetLocalNormals())[i];
  21194. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21195. return this;
  21196. };
  21197. /**
  21198. * 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)
  21199. * @param x defines x coordinate
  21200. * @param y defines y coordinate
  21201. * @param z defines z coordinate
  21202. * @returns the array of facet indexes
  21203. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21204. */
  21205. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21206. var bInfo = this.getBoundingInfo();
  21207. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21208. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21209. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21210. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21211. return null;
  21212. }
  21213. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21214. };
  21215. /**
  21216. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21217. * @param projected sets as the (x,y,z) world projection on the facet
  21218. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21219. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21220. * @param x defines x coordinate
  21221. * @param y defines y coordinate
  21222. * @param z defines z coordinate
  21223. * @returns the face index if found (or null instead)
  21224. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21225. */
  21226. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21227. if (checkFace === void 0) { checkFace = false; }
  21228. if (facing === void 0) { facing = true; }
  21229. var world = this.getWorldMatrix();
  21230. var invMat = BABYLON.Tmp.Matrix[5];
  21231. world.invertToRef(invMat);
  21232. var invVect = BABYLON.Tmp.Vector3[8];
  21233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21234. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21235. if (projected) {
  21236. // tranform the local computed projected vector to world coordinates
  21237. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21238. }
  21239. return closest;
  21240. };
  21241. /**
  21242. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21243. * @param projected sets as the (x,y,z) local projection on the facet
  21244. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21245. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21246. * @param x defines x coordinate
  21247. * @param y defines y coordinate
  21248. * @param z defines z coordinate
  21249. * @returns the face index if found (or null instead)
  21250. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21251. */
  21252. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21253. if (checkFace === void 0) { checkFace = false; }
  21254. if (facing === void 0) { facing = true; }
  21255. var closest = null;
  21256. var tmpx = 0.0;
  21257. var tmpy = 0.0;
  21258. var tmpz = 0.0;
  21259. var d = 0.0; // tmp dot facet normal * facet position
  21260. var t0 = 0.0;
  21261. var projx = 0.0;
  21262. var projy = 0.0;
  21263. var projz = 0.0;
  21264. // Get all the facets in the same partitioning block than (x, y, z)
  21265. var facetPositions = this.getFacetLocalPositions();
  21266. var facetNormals = this.getFacetLocalNormals();
  21267. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21268. if (!facetsInBlock) {
  21269. return null;
  21270. }
  21271. // Get the closest facet to (x, y, z)
  21272. var shortest = Number.MAX_VALUE; // init distance vars
  21273. var tmpDistance = shortest;
  21274. var fib; // current facet in the block
  21275. var norm; // current facet normal
  21276. var p0; // current facet barycenter position
  21277. // loop on all the facets in the current partitioning block
  21278. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21279. fib = facetsInBlock[idx];
  21280. norm = facetNormals[fib];
  21281. p0 = facetPositions[fib];
  21282. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21283. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21284. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21285. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21286. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21287. projx = x + norm.x * t0;
  21288. projy = y + norm.y * t0;
  21289. projz = z + norm.z * t0;
  21290. tmpx = projx - x;
  21291. tmpy = projy - y;
  21292. tmpz = projz - z;
  21293. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21294. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21295. shortest = tmpDistance;
  21296. closest = fib;
  21297. if (projected) {
  21298. projected.x = projx;
  21299. projected.y = projy;
  21300. projected.z = projz;
  21301. }
  21302. }
  21303. }
  21304. }
  21305. return closest;
  21306. };
  21307. /**
  21308. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21309. * @returns the parameters
  21310. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21311. */
  21312. AbstractMesh.prototype.getFacetDataParameters = function () {
  21313. return this._facetParameters;
  21314. };
  21315. /**
  21316. * Disables the feature FacetData and frees the related memory
  21317. * @returns the current mesh
  21318. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21319. */
  21320. AbstractMesh.prototype.disableFacetData = function () {
  21321. if (this._facetDataEnabled) {
  21322. this._facetDataEnabled = false;
  21323. this._facetPositions = new Array();
  21324. this._facetNormals = new Array();
  21325. this._facetPartitioning = new Array();
  21326. this._facetParameters = null;
  21327. this._depthSortedIndices = new Uint32Array(0);
  21328. }
  21329. return this;
  21330. };
  21331. /**
  21332. * Updates the AbstractMesh indices array
  21333. * @param indices defines the data source
  21334. * @returns the current mesh
  21335. */
  21336. AbstractMesh.prototype.updateIndices = function (indices) {
  21337. return this;
  21338. };
  21339. /**
  21340. * Creates new normals data for the mesh
  21341. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21342. * @returns the current mesh
  21343. */
  21344. AbstractMesh.prototype.createNormals = function (updatable) {
  21345. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21346. var indices = this.getIndices();
  21347. var normals;
  21348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21349. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21350. }
  21351. else {
  21352. normals = [];
  21353. }
  21354. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21355. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21356. return this;
  21357. };
  21358. /**
  21359. * Align the mesh with a normal
  21360. * @param normal defines the normal to use
  21361. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21362. * @returns the current mesh
  21363. */
  21364. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21365. if (!upDirection) {
  21366. upDirection = BABYLON.Axis.Y;
  21367. }
  21368. var axisX = BABYLON.Tmp.Vector3[0];
  21369. var axisZ = BABYLON.Tmp.Vector3[1];
  21370. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21371. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21372. if (this.rotationQuaternion) {
  21373. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21374. }
  21375. else {
  21376. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21377. }
  21378. return this;
  21379. };
  21380. /** @hidden */
  21381. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21382. this._isOccluded = false;
  21383. };
  21384. /** No occlusion */
  21385. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21386. /** Occlusion set to optimisitic */
  21387. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21388. /** Occlusion set to strict */
  21389. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21390. /** Use an accurante occlusion algorithm */
  21391. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21392. /** Use a conservative occlusion algorithm */
  21393. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21394. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21395. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21396. /** Culling strategy with bounding sphere only and then frustum culling */
  21397. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21398. return AbstractMesh;
  21399. }(BABYLON.TransformNode));
  21400. BABYLON.AbstractMesh = AbstractMesh;
  21401. })(BABYLON || (BABYLON = {}));
  21402. //# sourceMappingURL=babylon.abstractMesh.js.map
  21403. var BABYLON;
  21404. (function (BABYLON) {
  21405. /**
  21406. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21407. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21408. * 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.
  21409. */
  21410. var Light = /** @class */ (function (_super) {
  21411. __extends(Light, _super);
  21412. /**
  21413. * Creates a Light object in the scene.
  21414. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21415. * @param name The firendly name of the light
  21416. * @param scene The scene the light belongs too
  21417. */
  21418. function Light(name, scene) {
  21419. var _this = _super.call(this, name, scene) || this;
  21420. /**
  21421. * Diffuse gives the basic color to an object.
  21422. */
  21423. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21424. /**
  21425. * Specular produces a highlight color on an object.
  21426. * Note: This is note affecting PBR materials.
  21427. */
  21428. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21429. /**
  21430. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21431. * falling off base on range or angle.
  21432. * This can be set to any values in Light.FALLOFF_x.
  21433. *
  21434. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21435. * other types of materials.
  21436. */
  21437. _this.falloffType = Light.FALLOFF_DEFAULT;
  21438. /**
  21439. * Strength of the light.
  21440. * Note: By default it is define in the framework own unit.
  21441. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21442. */
  21443. _this.intensity = 1.0;
  21444. _this._range = Number.MAX_VALUE;
  21445. _this._inverseSquaredRange = 0;
  21446. /**
  21447. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21448. * of light.
  21449. */
  21450. _this._photometricScale = 1.0;
  21451. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21452. _this._radius = 0.00001;
  21453. /**
  21454. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21455. * exceeding the number allowed of the materials.
  21456. */
  21457. _this.renderPriority = 0;
  21458. _this._shadowEnabled = true;
  21459. _this._excludeWithLayerMask = 0;
  21460. _this._includeOnlyWithLayerMask = 0;
  21461. _this._lightmapMode = 0;
  21462. /**
  21463. * @hidden Internal use only.
  21464. */
  21465. _this._excludedMeshesIds = new Array();
  21466. /**
  21467. * @hidden Internal use only.
  21468. */
  21469. _this._includedOnlyMeshesIds = new Array();
  21470. _this.getScene().addLight(_this);
  21471. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21472. _this._buildUniformLayout();
  21473. _this.includedOnlyMeshes = new Array();
  21474. _this.excludedMeshes = new Array();
  21475. _this._resyncMeshes();
  21476. return _this;
  21477. }
  21478. Object.defineProperty(Light.prototype, "range", {
  21479. /**
  21480. * Defines how far from the source the light is impacting in scene units.
  21481. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21482. */
  21483. get: function () {
  21484. return this._range;
  21485. },
  21486. /**
  21487. * Defines how far from the source the light is impacting in scene units.
  21488. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21489. */
  21490. set: function (value) {
  21491. this._range = value;
  21492. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Light.prototype, "intensityMode", {
  21498. /**
  21499. * Gets the photometric scale used to interpret the intensity.
  21500. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21501. */
  21502. get: function () {
  21503. return this._intensityMode;
  21504. },
  21505. /**
  21506. * Sets the photometric scale used to interpret the intensity.
  21507. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21508. */
  21509. set: function (value) {
  21510. this._intensityMode = value;
  21511. this._computePhotometricScale();
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. ;
  21517. ;
  21518. Object.defineProperty(Light.prototype, "radius", {
  21519. /**
  21520. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21521. */
  21522. get: function () {
  21523. return this._radius;
  21524. },
  21525. /**
  21526. * sets the light radius used by PBR Materials to simulate soft area lights.
  21527. */
  21528. set: function (value) {
  21529. this._radius = value;
  21530. this._computePhotometricScale();
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. ;
  21536. ;
  21537. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21538. /**
  21539. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21540. * the current shadow generator.
  21541. */
  21542. get: function () {
  21543. return this._shadowEnabled;
  21544. },
  21545. /**
  21546. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21547. * the current shadow generator.
  21548. */
  21549. set: function (value) {
  21550. if (this._shadowEnabled === value) {
  21551. return;
  21552. }
  21553. this._shadowEnabled = value;
  21554. this._markMeshesAsLightDirty();
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21560. /**
  21561. * Gets the only meshes impacted by this light.
  21562. */
  21563. get: function () {
  21564. return this._includedOnlyMeshes;
  21565. },
  21566. /**
  21567. * Sets the only meshes impacted by this light.
  21568. */
  21569. set: function (value) {
  21570. this._includedOnlyMeshes = value;
  21571. this._hookArrayForIncludedOnly(value);
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21577. /**
  21578. * Gets the meshes not impacted by this light.
  21579. */
  21580. get: function () {
  21581. return this._excludedMeshes;
  21582. },
  21583. /**
  21584. * Sets the meshes not impacted by this light.
  21585. */
  21586. set: function (value) {
  21587. this._excludedMeshes = value;
  21588. this._hookArrayForExcluded(value);
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21594. /**
  21595. * Gets the layer id use to find what meshes are not impacted by the light.
  21596. * Inactive if 0
  21597. */
  21598. get: function () {
  21599. return this._excludeWithLayerMask;
  21600. },
  21601. /**
  21602. * Sets the layer id use to find what meshes are not impacted by the light.
  21603. * Inactive if 0
  21604. */
  21605. set: function (value) {
  21606. this._excludeWithLayerMask = value;
  21607. this._resyncMeshes();
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21613. /**
  21614. * Gets the layer id use to find what meshes are impacted by the light.
  21615. * Inactive if 0
  21616. */
  21617. get: function () {
  21618. return this._includeOnlyWithLayerMask;
  21619. },
  21620. /**
  21621. * Sets the layer id use to find what meshes are impacted by the light.
  21622. * Inactive if 0
  21623. */
  21624. set: function (value) {
  21625. this._includeOnlyWithLayerMask = value;
  21626. this._resyncMeshes();
  21627. },
  21628. enumerable: true,
  21629. configurable: true
  21630. });
  21631. Object.defineProperty(Light.prototype, "lightmapMode", {
  21632. /**
  21633. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21634. */
  21635. get: function () {
  21636. return this._lightmapMode;
  21637. },
  21638. /**
  21639. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21640. */
  21641. set: function (value) {
  21642. if (this._lightmapMode === value) {
  21643. return;
  21644. }
  21645. this._lightmapMode = value;
  21646. this._markMeshesAsLightDirty();
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. /**
  21652. * Returns the string "Light".
  21653. * @returns the class name
  21654. */
  21655. Light.prototype.getClassName = function () {
  21656. return "Light";
  21657. };
  21658. /**
  21659. * Converts the light information to a readable string for debug purpose.
  21660. * @param fullDetails Supports for multiple levels of logging within scene loading
  21661. * @returns the human readable light info
  21662. */
  21663. Light.prototype.toString = function (fullDetails) {
  21664. var ret = "Name: " + this.name;
  21665. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21666. if (this.animations) {
  21667. for (var i = 0; i < this.animations.length; i++) {
  21668. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21669. }
  21670. }
  21671. if (fullDetails) {
  21672. }
  21673. return ret;
  21674. };
  21675. /**
  21676. * Set the enabled state of this node.
  21677. * @param value - the new enabled state
  21678. */
  21679. Light.prototype.setEnabled = function (value) {
  21680. _super.prototype.setEnabled.call(this, value);
  21681. this._resyncMeshes();
  21682. };
  21683. /**
  21684. * Returns the Light associated shadow generator if any.
  21685. * @return the associated shadow generator.
  21686. */
  21687. Light.prototype.getShadowGenerator = function () {
  21688. return this._shadowGenerator;
  21689. };
  21690. /**
  21691. * Returns a Vector3, the absolute light position in the World.
  21692. * @returns the world space position of the light
  21693. */
  21694. Light.prototype.getAbsolutePosition = function () {
  21695. return BABYLON.Vector3.Zero();
  21696. };
  21697. /**
  21698. * Specifies if the light will affect the passed mesh.
  21699. * @param mesh The mesh to test against the light
  21700. * @return true the mesh is affected otherwise, false.
  21701. */
  21702. Light.prototype.canAffectMesh = function (mesh) {
  21703. if (!mesh) {
  21704. return true;
  21705. }
  21706. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21707. return false;
  21708. }
  21709. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21710. return false;
  21711. }
  21712. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21713. return false;
  21714. }
  21715. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21716. return false;
  21717. }
  21718. return true;
  21719. };
  21720. /**
  21721. * Computes and Returns the light World matrix.
  21722. * @returns the world matrix
  21723. */
  21724. Light.prototype.getWorldMatrix = function () {
  21725. this._currentRenderId = this.getScene().getRenderId();
  21726. this._childRenderId = this._currentRenderId;
  21727. var worldMatrix = this._getWorldMatrix();
  21728. if (this.parent && this.parent.getWorldMatrix) {
  21729. if (!this._parentedWorldMatrix) {
  21730. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21731. }
  21732. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21733. this._markSyncedWithParent();
  21734. return this._parentedWorldMatrix;
  21735. }
  21736. return worldMatrix;
  21737. };
  21738. /**
  21739. * Sort function to order lights for rendering.
  21740. * @param a First Light object to compare to second.
  21741. * @param b Second Light object to compare first.
  21742. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21743. */
  21744. Light.CompareLightsPriority = function (a, b) {
  21745. //shadow-casting lights have priority over non-shadow-casting lights
  21746. //the renderPrioirty is a secondary sort criterion
  21747. if (a.shadowEnabled !== b.shadowEnabled) {
  21748. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21749. }
  21750. return b.renderPriority - a.renderPriority;
  21751. };
  21752. /**
  21753. * Releases resources associated with this node.
  21754. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21755. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21756. */
  21757. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21758. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21759. if (this._shadowGenerator) {
  21760. this._shadowGenerator.dispose();
  21761. this._shadowGenerator = null;
  21762. }
  21763. // Animations
  21764. this.getScene().stopAnimation(this);
  21765. // Remove from meshes
  21766. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21767. var mesh = _a[_i];
  21768. mesh._removeLightSource(this);
  21769. }
  21770. this._uniformBuffer.dispose();
  21771. // Remove from scene
  21772. this.getScene().removeLight(this);
  21773. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21774. };
  21775. /**
  21776. * Returns the light type ID (integer).
  21777. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21778. */
  21779. Light.prototype.getTypeID = function () {
  21780. return 0;
  21781. };
  21782. /**
  21783. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21784. * @returns the scaled intensity in intensity mode unit
  21785. */
  21786. Light.prototype.getScaledIntensity = function () {
  21787. return this._photometricScale * this.intensity;
  21788. };
  21789. /**
  21790. * Returns a new Light object, named "name", from the current one.
  21791. * @param name The name of the cloned light
  21792. * @returns the new created light
  21793. */
  21794. Light.prototype.clone = function (name) {
  21795. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21796. if (!constructor) {
  21797. return null;
  21798. }
  21799. return BABYLON.SerializationHelper.Clone(constructor, this);
  21800. };
  21801. /**
  21802. * Serializes the current light into a Serialization object.
  21803. * @returns the serialized object.
  21804. */
  21805. Light.prototype.serialize = function () {
  21806. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21807. // Type
  21808. serializationObject.type = this.getTypeID();
  21809. // Parent
  21810. if (this.parent) {
  21811. serializationObject.parentId = this.parent.id;
  21812. }
  21813. // Inclusion / exclusions
  21814. if (this.excludedMeshes.length > 0) {
  21815. serializationObject.excludedMeshesIds = [];
  21816. this.excludedMeshes.forEach(function (mesh) {
  21817. serializationObject.excludedMeshesIds.push(mesh.id);
  21818. });
  21819. }
  21820. if (this.includedOnlyMeshes.length > 0) {
  21821. serializationObject.includedOnlyMeshesIds = [];
  21822. this.includedOnlyMeshes.forEach(function (mesh) {
  21823. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21824. });
  21825. }
  21826. // Animations
  21827. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21828. serializationObject.ranges = this.serializeAnimationRanges();
  21829. return serializationObject;
  21830. };
  21831. /**
  21832. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21833. * This new light is named "name" and added to the passed scene.
  21834. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21835. * @param name The friendly name of the light
  21836. * @param scene The scene the new light will belong to
  21837. * @returns the constructor function
  21838. */
  21839. Light.GetConstructorFromName = function (type, name, scene) {
  21840. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21841. if (constructorFunc) {
  21842. return constructorFunc;
  21843. }
  21844. // Default to no light for none present once.
  21845. return null;
  21846. };
  21847. /**
  21848. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21849. * @param parsedLight The JSON representation of the light
  21850. * @param scene The scene to create the parsed light in
  21851. * @returns the created light after parsing
  21852. */
  21853. Light.Parse = function (parsedLight, scene) {
  21854. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21855. if (!constructor) {
  21856. return null;
  21857. }
  21858. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21859. // Inclusion / exclusions
  21860. if (parsedLight.excludedMeshesIds) {
  21861. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21862. }
  21863. if (parsedLight.includedOnlyMeshesIds) {
  21864. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21865. }
  21866. // Parent
  21867. if (parsedLight.parentId) {
  21868. light._waitingParentId = parsedLight.parentId;
  21869. }
  21870. // Animations
  21871. if (parsedLight.animations) {
  21872. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21873. var parsedAnimation = parsedLight.animations[animationIndex];
  21874. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21875. }
  21876. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21877. }
  21878. if (parsedLight.autoAnimate) {
  21879. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21880. }
  21881. return light;
  21882. };
  21883. Light.prototype._hookArrayForExcluded = function (array) {
  21884. var _this = this;
  21885. var oldPush = array.push;
  21886. array.push = function () {
  21887. var items = [];
  21888. for (var _i = 0; _i < arguments.length; _i++) {
  21889. items[_i] = arguments[_i];
  21890. }
  21891. var result = oldPush.apply(array, items);
  21892. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21893. var item = items_1[_a];
  21894. item._resyncLighSource(_this);
  21895. }
  21896. return result;
  21897. };
  21898. var oldSplice = array.splice;
  21899. array.splice = function (index, deleteCount) {
  21900. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21901. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21902. var item = deleted_1[_i];
  21903. item._resyncLighSource(_this);
  21904. }
  21905. return deleted;
  21906. };
  21907. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21908. var item = array_1[_i];
  21909. item._resyncLighSource(this);
  21910. }
  21911. };
  21912. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21913. var _this = this;
  21914. var oldPush = array.push;
  21915. array.push = function () {
  21916. var items = [];
  21917. for (var _i = 0; _i < arguments.length; _i++) {
  21918. items[_i] = arguments[_i];
  21919. }
  21920. var result = oldPush.apply(array, items);
  21921. _this._resyncMeshes();
  21922. return result;
  21923. };
  21924. var oldSplice = array.splice;
  21925. array.splice = function (index, deleteCount) {
  21926. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21927. _this._resyncMeshes();
  21928. return deleted;
  21929. };
  21930. this._resyncMeshes();
  21931. };
  21932. Light.prototype._resyncMeshes = function () {
  21933. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21934. var mesh = _a[_i];
  21935. mesh._resyncLighSource(this);
  21936. }
  21937. };
  21938. /**
  21939. * Forces the meshes to update their light related information in their rendering used effects
  21940. * @hidden Internal Use Only
  21941. */
  21942. Light.prototype._markMeshesAsLightDirty = function () {
  21943. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21944. var mesh = _a[_i];
  21945. if (mesh._lightSources.indexOf(this) !== -1) {
  21946. mesh._markSubMeshesAsLightDirty();
  21947. }
  21948. }
  21949. };
  21950. /**
  21951. * Recomputes the cached photometric scale if needed.
  21952. */
  21953. Light.prototype._computePhotometricScale = function () {
  21954. this._photometricScale = this._getPhotometricScale();
  21955. this.getScene().resetCachedMaterial();
  21956. };
  21957. /**
  21958. * Returns the Photometric Scale according to the light type and intensity mode.
  21959. */
  21960. Light.prototype._getPhotometricScale = function () {
  21961. var photometricScale = 0.0;
  21962. var lightTypeID = this.getTypeID();
  21963. //get photometric mode
  21964. var photometricMode = this.intensityMode;
  21965. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21966. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21967. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21968. }
  21969. else {
  21970. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21971. }
  21972. }
  21973. //compute photometric scale
  21974. switch (lightTypeID) {
  21975. case Light.LIGHTTYPEID_POINTLIGHT:
  21976. case Light.LIGHTTYPEID_SPOTLIGHT:
  21977. switch (photometricMode) {
  21978. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21979. photometricScale = 1.0 / (4.0 * Math.PI);
  21980. break;
  21981. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21982. photometricScale = 1.0;
  21983. break;
  21984. case Light.INTENSITYMODE_LUMINANCE:
  21985. photometricScale = this.radius * this.radius;
  21986. break;
  21987. }
  21988. break;
  21989. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21990. switch (photometricMode) {
  21991. case Light.INTENSITYMODE_ILLUMINANCE:
  21992. photometricScale = 1.0;
  21993. break;
  21994. case Light.INTENSITYMODE_LUMINANCE:
  21995. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21996. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21997. var apexAngleRadians = this.radius;
  21998. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21999. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22000. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22001. photometricScale = solidAngle;
  22002. break;
  22003. }
  22004. break;
  22005. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22006. // No fall off in hemisperic light.
  22007. photometricScale = 1.0;
  22008. break;
  22009. }
  22010. return photometricScale;
  22011. };
  22012. /**
  22013. * Reorder the light in the scene according to their defined priority.
  22014. * @hidden Internal Use Only
  22015. */
  22016. Light.prototype._reorderLightsInScene = function () {
  22017. var scene = this.getScene();
  22018. if (this._renderPriority != 0) {
  22019. scene.requireLightSorting = true;
  22020. }
  22021. this.getScene().sortLightsByPriority();
  22022. };
  22023. /**
  22024. * Falloff Default: light is falling off following the material specification:
  22025. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22026. */
  22027. Light.FALLOFF_DEFAULT = 0;
  22028. /**
  22029. * Falloff Physical: light is falling off following the inverse squared distance law.
  22030. */
  22031. Light.FALLOFF_PHYSICAL = 1;
  22032. /**
  22033. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22034. * to enhance interoperability with other engines.
  22035. */
  22036. Light.FALLOFF_GLTF = 2;
  22037. /**
  22038. * Falloff Standard: light is falling off like in the standard material
  22039. * to enhance interoperability with other materials.
  22040. */
  22041. Light.FALLOFF_STANDARD = 3;
  22042. //lightmapMode Consts
  22043. /**
  22044. * If every light affecting the material is in this lightmapMode,
  22045. * material.lightmapTexture adds or multiplies
  22046. * (depends on material.useLightmapAsShadowmap)
  22047. * after every other light calculations.
  22048. */
  22049. Light.LIGHTMAP_DEFAULT = 0;
  22050. /**
  22051. * material.lightmapTexture as only diffuse lighting from this light
  22052. * adds only specular lighting from this light
  22053. * adds dynamic shadows
  22054. */
  22055. Light.LIGHTMAP_SPECULAR = 1;
  22056. /**
  22057. * material.lightmapTexture as only lighting
  22058. * no light calculation from this light
  22059. * only adds dynamic shadows from this light
  22060. */
  22061. Light.LIGHTMAP_SHADOWSONLY = 2;
  22062. // Intensity Mode Consts
  22063. /**
  22064. * Each light type uses the default quantity according to its type:
  22065. * point/spot lights use luminous intensity
  22066. * directional lights use illuminance
  22067. */
  22068. Light.INTENSITYMODE_AUTOMATIC = 0;
  22069. /**
  22070. * lumen (lm)
  22071. */
  22072. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22073. /**
  22074. * candela (lm/sr)
  22075. */
  22076. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22077. /**
  22078. * lux (lm/m^2)
  22079. */
  22080. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22081. /**
  22082. * nit (cd/m^2)
  22083. */
  22084. Light.INTENSITYMODE_LUMINANCE = 4;
  22085. // Light types ids const.
  22086. /**
  22087. * Light type const id of the point light.
  22088. */
  22089. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22090. /**
  22091. * Light type const id of the directional light.
  22092. */
  22093. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22094. /**
  22095. * Light type const id of the spot light.
  22096. */
  22097. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22098. /**
  22099. * Light type const id of the hemispheric light.
  22100. */
  22101. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22102. __decorate([
  22103. BABYLON.serializeAsColor3()
  22104. ], Light.prototype, "diffuse", void 0);
  22105. __decorate([
  22106. BABYLON.serializeAsColor3()
  22107. ], Light.prototype, "specular", void 0);
  22108. __decorate([
  22109. BABYLON.serialize()
  22110. ], Light.prototype, "falloffType", void 0);
  22111. __decorate([
  22112. BABYLON.serialize()
  22113. ], Light.prototype, "intensity", void 0);
  22114. __decorate([
  22115. BABYLON.serialize()
  22116. ], Light.prototype, "range", null);
  22117. __decorate([
  22118. BABYLON.serialize()
  22119. ], Light.prototype, "intensityMode", null);
  22120. __decorate([
  22121. BABYLON.serialize()
  22122. ], Light.prototype, "radius", null);
  22123. __decorate([
  22124. BABYLON.serialize()
  22125. ], Light.prototype, "_renderPriority", void 0);
  22126. __decorate([
  22127. BABYLON.expandToProperty("_reorderLightsInScene")
  22128. ], Light.prototype, "renderPriority", void 0);
  22129. __decorate([
  22130. BABYLON.serialize("shadowEnabled")
  22131. ], Light.prototype, "_shadowEnabled", void 0);
  22132. __decorate([
  22133. BABYLON.serialize("excludeWithLayerMask")
  22134. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22135. __decorate([
  22136. BABYLON.serialize("includeOnlyWithLayerMask")
  22137. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22138. __decorate([
  22139. BABYLON.serialize("lightmapMode")
  22140. ], Light.prototype, "_lightmapMode", void 0);
  22141. return Light;
  22142. }(BABYLON.Node));
  22143. BABYLON.Light = Light;
  22144. })(BABYLON || (BABYLON = {}));
  22145. //# sourceMappingURL=babylon.light.js.map
  22146. var BABYLON;
  22147. (function (BABYLON) {
  22148. var Camera = /** @class */ (function (_super) {
  22149. __extends(Camera, _super);
  22150. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22151. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22152. var _this = _super.call(this, name, scene) || this;
  22153. /**
  22154. * The vector the camera should consider as up.
  22155. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22156. */
  22157. _this.upVector = BABYLON.Vector3.Up();
  22158. _this.orthoLeft = null;
  22159. _this.orthoRight = null;
  22160. _this.orthoBottom = null;
  22161. _this.orthoTop = null;
  22162. /**
  22163. * FOV is set in Radians. (default is 0.8)
  22164. */
  22165. _this.fov = 0.8;
  22166. _this.minZ = 1;
  22167. _this.maxZ = 10000.0;
  22168. _this.inertia = 0.9;
  22169. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22170. _this.isIntermediate = false;
  22171. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22172. /**
  22173. * Restricts the camera to viewing objects with the same layerMask.
  22174. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22175. */
  22176. _this.layerMask = 0x0FFFFFFF;
  22177. /**
  22178. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22179. */
  22180. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22181. // Camera rig members
  22182. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22183. /** @hidden */
  22184. _this._rigCameras = new Array();
  22185. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22186. /** @hidden */
  22187. _this._skipRendering = false;
  22188. _this.customRenderTargets = new Array();
  22189. // Observables
  22190. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22191. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22192. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22193. _this.onRestoreStateObservable = new BABYLON.Observable();
  22194. // Cache
  22195. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22196. _this._projectionMatrix = new BABYLON.Matrix();
  22197. _this._doNotComputeProjectionMatrix = false;
  22198. _this._worldMatrix = BABYLON.Matrix.Identity();
  22199. _this._postProcesses = new Array();
  22200. _this._transformMatrix = BABYLON.Matrix.Zero();
  22201. _this._activeMeshes = new BABYLON.SmartArray(256);
  22202. _this._globalPosition = BABYLON.Vector3.Zero();
  22203. _this._refreshFrustumPlanes = true;
  22204. _this.getScene().addCamera(_this);
  22205. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22206. _this.getScene().activeCamera = _this;
  22207. }
  22208. _this.position = position;
  22209. return _this;
  22210. }
  22211. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22212. get: function () {
  22213. return Camera._PERSPECTIVE_CAMERA;
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22219. get: function () {
  22220. return Camera._ORTHOGRAPHIC_CAMERA;
  22221. },
  22222. enumerable: true,
  22223. configurable: true
  22224. });
  22225. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22226. /**
  22227. * This is the default FOV mode for perspective cameras.
  22228. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22229. *
  22230. */
  22231. get: function () {
  22232. return Camera._FOVMODE_VERTICAL_FIXED;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22238. /**
  22239. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22240. *
  22241. */
  22242. get: function () {
  22243. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22244. },
  22245. enumerable: true,
  22246. configurable: true
  22247. });
  22248. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22249. get: function () {
  22250. return Camera._RIG_MODE_NONE;
  22251. },
  22252. enumerable: true,
  22253. configurable: true
  22254. });
  22255. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22256. get: function () {
  22257. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22258. },
  22259. enumerable: true,
  22260. configurable: true
  22261. });
  22262. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22263. get: function () {
  22264. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22270. get: function () {
  22271. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22277. get: function () {
  22278. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22284. get: function () {
  22285. return Camera._RIG_MODE_VR;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22291. get: function () {
  22292. return Camera._RIG_MODE_WEBVR;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. /**
  22298. * Store current camera state (fov, position, etc..)
  22299. */
  22300. Camera.prototype.storeState = function () {
  22301. this._stateStored = true;
  22302. this._storedFov = this.fov;
  22303. return this;
  22304. };
  22305. /**
  22306. * Restores the camera state values if it has been stored. You must call storeState() first
  22307. */
  22308. Camera.prototype._restoreStateValues = function () {
  22309. if (!this._stateStored) {
  22310. return false;
  22311. }
  22312. this.fov = this._storedFov;
  22313. return true;
  22314. };
  22315. /**
  22316. * Restored camera state. You must call storeState() first
  22317. */
  22318. Camera.prototype.restoreState = function () {
  22319. if (this._restoreStateValues()) {
  22320. this.onRestoreStateObservable.notifyObservers(this);
  22321. return true;
  22322. }
  22323. return false;
  22324. };
  22325. Camera.prototype.getClassName = function () {
  22326. return "Camera";
  22327. };
  22328. /**
  22329. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22330. */
  22331. Camera.prototype.toString = function (fullDetails) {
  22332. var ret = "Name: " + this.name;
  22333. ret += ", type: " + this.getClassName();
  22334. if (this.animations) {
  22335. for (var i = 0; i < this.animations.length; i++) {
  22336. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22337. }
  22338. }
  22339. if (fullDetails) {
  22340. }
  22341. return ret;
  22342. };
  22343. Object.defineProperty(Camera.prototype, "globalPosition", {
  22344. get: function () {
  22345. return this._globalPosition;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. Camera.prototype.getActiveMeshes = function () {
  22351. return this._activeMeshes;
  22352. };
  22353. Camera.prototype.isActiveMesh = function (mesh) {
  22354. return (this._activeMeshes.indexOf(mesh) !== -1);
  22355. };
  22356. /**
  22357. * Is this camera ready to be used/rendered
  22358. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22359. * @return true if the camera is ready
  22360. */
  22361. Camera.prototype.isReady = function (completeCheck) {
  22362. if (completeCheck === void 0) { completeCheck = false; }
  22363. if (completeCheck) {
  22364. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22365. var pp = _a[_i];
  22366. if (pp && !pp.isReady()) {
  22367. return false;
  22368. }
  22369. }
  22370. }
  22371. return _super.prototype.isReady.call(this, completeCheck);
  22372. };
  22373. //Cache
  22374. /** @hidden */
  22375. Camera.prototype._initCache = function () {
  22376. _super.prototype._initCache.call(this);
  22377. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22378. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22379. this._cache.mode = undefined;
  22380. this._cache.minZ = undefined;
  22381. this._cache.maxZ = undefined;
  22382. this._cache.fov = undefined;
  22383. this._cache.fovMode = undefined;
  22384. this._cache.aspectRatio = undefined;
  22385. this._cache.orthoLeft = undefined;
  22386. this._cache.orthoRight = undefined;
  22387. this._cache.orthoBottom = undefined;
  22388. this._cache.orthoTop = undefined;
  22389. this._cache.renderWidth = undefined;
  22390. this._cache.renderHeight = undefined;
  22391. };
  22392. /** @hidden */
  22393. Camera.prototype._updateCache = function (ignoreParentClass) {
  22394. if (!ignoreParentClass) {
  22395. _super.prototype._updateCache.call(this);
  22396. }
  22397. this._cache.position.copyFrom(this.position);
  22398. this._cache.upVector.copyFrom(this.upVector);
  22399. };
  22400. // Synchronized
  22401. /** @hidden */
  22402. Camera.prototype._isSynchronized = function () {
  22403. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22404. };
  22405. /** @hidden */
  22406. Camera.prototype._isSynchronizedViewMatrix = function () {
  22407. if (!_super.prototype._isSynchronized.call(this))
  22408. return false;
  22409. return this._cache.position.equals(this.position)
  22410. && this._cache.upVector.equals(this.upVector)
  22411. && this.isSynchronizedWithParent();
  22412. };
  22413. /** @hidden */
  22414. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22415. var check = this._cache.mode === this.mode
  22416. && this._cache.minZ === this.minZ
  22417. && this._cache.maxZ === this.maxZ;
  22418. if (!check) {
  22419. return false;
  22420. }
  22421. var engine = this.getEngine();
  22422. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22423. check = this._cache.fov === this.fov
  22424. && this._cache.fovMode === this.fovMode
  22425. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22426. }
  22427. else {
  22428. check = this._cache.orthoLeft === this.orthoLeft
  22429. && this._cache.orthoRight === this.orthoRight
  22430. && this._cache.orthoBottom === this.orthoBottom
  22431. && this._cache.orthoTop === this.orthoTop
  22432. && this._cache.renderWidth === engine.getRenderWidth()
  22433. && this._cache.renderHeight === engine.getRenderHeight();
  22434. }
  22435. return check;
  22436. };
  22437. // Controls
  22438. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22439. };
  22440. Camera.prototype.detachControl = function (element) {
  22441. };
  22442. Camera.prototype.update = function () {
  22443. this._checkInputs();
  22444. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22445. this._updateRigCameras();
  22446. }
  22447. };
  22448. /** @hidden */
  22449. Camera.prototype._checkInputs = function () {
  22450. this.onAfterCheckInputsObservable.notifyObservers(this);
  22451. };
  22452. Object.defineProperty(Camera.prototype, "rigCameras", {
  22453. get: function () {
  22454. return this._rigCameras;
  22455. },
  22456. enumerable: true,
  22457. configurable: true
  22458. });
  22459. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22460. get: function () {
  22461. return this._rigPostProcess;
  22462. },
  22463. enumerable: true,
  22464. configurable: true
  22465. });
  22466. /**
  22467. * Internal, gets the first post proces.
  22468. * @returns the first post process to be run on this camera.
  22469. */
  22470. Camera.prototype._getFirstPostProcess = function () {
  22471. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22472. if (this._postProcesses[ppIndex] !== null) {
  22473. return this._postProcesses[ppIndex];
  22474. }
  22475. }
  22476. return null;
  22477. };
  22478. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22479. // invalidate framebuffer
  22480. var firstPostProcess = this._getFirstPostProcess();
  22481. if (firstPostProcess) {
  22482. firstPostProcess.markTextureDirty();
  22483. }
  22484. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22485. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22486. var cam = this._rigCameras[i];
  22487. var rigPostProcess = cam._rigPostProcess;
  22488. // for VR rig, there does not have to be a post process
  22489. if (rigPostProcess) {
  22490. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22491. if (isPass) {
  22492. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22493. cam.isIntermediate = this._postProcesses.length === 0;
  22494. }
  22495. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22496. rigPostProcess.markTextureDirty();
  22497. }
  22498. else {
  22499. cam._postProcesses = this._postProcesses.slice(0);
  22500. }
  22501. }
  22502. };
  22503. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22504. if (insertAt === void 0) { insertAt = null; }
  22505. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22506. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22507. return 0;
  22508. }
  22509. if (insertAt == null || insertAt < 0) {
  22510. this._postProcesses.push(postProcess);
  22511. }
  22512. else if (this._postProcesses[insertAt] === null) {
  22513. this._postProcesses[insertAt] = postProcess;
  22514. }
  22515. else {
  22516. this._postProcesses.splice(insertAt, 0, postProcess);
  22517. }
  22518. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22519. return this._postProcesses.indexOf(postProcess);
  22520. };
  22521. Camera.prototype.detachPostProcess = function (postProcess) {
  22522. var idx = this._postProcesses.indexOf(postProcess);
  22523. if (idx !== -1) {
  22524. this._postProcesses[idx] = null;
  22525. }
  22526. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22527. };
  22528. Camera.prototype.getWorldMatrix = function () {
  22529. if (this._isSynchronizedViewMatrix()) {
  22530. return this._worldMatrix;
  22531. }
  22532. // Getting the the view matrix will also compute the world matrix.
  22533. this.getViewMatrix();
  22534. return this._worldMatrix;
  22535. };
  22536. /** @hidden */
  22537. Camera.prototype._getViewMatrix = function () {
  22538. return BABYLON.Matrix.Identity();
  22539. };
  22540. Camera.prototype.getViewMatrix = function (force) {
  22541. if (!force && this._isSynchronizedViewMatrix()) {
  22542. return this._computedViewMatrix;
  22543. }
  22544. this.updateCache();
  22545. this._computedViewMatrix = this._getViewMatrix();
  22546. this._currentRenderId = this.getScene().getRenderId();
  22547. this._childRenderId = this._currentRenderId;
  22548. this._refreshFrustumPlanes = true;
  22549. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22550. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22551. }
  22552. this.onViewMatrixChangedObservable.notifyObservers(this);
  22553. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22554. return this._computedViewMatrix;
  22555. };
  22556. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22557. this._doNotComputeProjectionMatrix = true;
  22558. if (projection !== undefined) {
  22559. this._projectionMatrix = projection;
  22560. }
  22561. };
  22562. ;
  22563. Camera.prototype.unfreezeProjectionMatrix = function () {
  22564. this._doNotComputeProjectionMatrix = false;
  22565. };
  22566. ;
  22567. Camera.prototype.getProjectionMatrix = function (force) {
  22568. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22569. return this._projectionMatrix;
  22570. }
  22571. // Cache
  22572. this._cache.mode = this.mode;
  22573. this._cache.minZ = this.minZ;
  22574. this._cache.maxZ = this.maxZ;
  22575. // Matrix
  22576. this._refreshFrustumPlanes = true;
  22577. var engine = this.getEngine();
  22578. var scene = this.getScene();
  22579. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22580. this._cache.fov = this.fov;
  22581. this._cache.fovMode = this.fovMode;
  22582. this._cache.aspectRatio = engine.getAspectRatio(this);
  22583. if (this.minZ <= 0) {
  22584. this.minZ = 0.1;
  22585. }
  22586. if (scene.useRightHandedSystem) {
  22587. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22588. }
  22589. else {
  22590. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22591. }
  22592. }
  22593. else {
  22594. var halfWidth = engine.getRenderWidth() / 2.0;
  22595. var halfHeight = engine.getRenderHeight() / 2.0;
  22596. if (scene.useRightHandedSystem) {
  22597. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22598. }
  22599. else {
  22600. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22601. }
  22602. this._cache.orthoLeft = this.orthoLeft;
  22603. this._cache.orthoRight = this.orthoRight;
  22604. this._cache.orthoBottom = this.orthoBottom;
  22605. this._cache.orthoTop = this.orthoTop;
  22606. this._cache.renderWidth = engine.getRenderWidth();
  22607. this._cache.renderHeight = engine.getRenderHeight();
  22608. }
  22609. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22610. return this._projectionMatrix;
  22611. };
  22612. /**
  22613. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22614. * @returns a Matrix
  22615. */
  22616. Camera.prototype.getTransformationMatrix = function () {
  22617. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22618. return this._transformMatrix;
  22619. };
  22620. Camera.prototype.updateFrustumPlanes = function () {
  22621. if (!this._refreshFrustumPlanes) {
  22622. return;
  22623. }
  22624. this.getTransformationMatrix();
  22625. if (!this._frustumPlanes) {
  22626. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22627. }
  22628. else {
  22629. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22630. }
  22631. this._refreshFrustumPlanes = false;
  22632. };
  22633. Camera.prototype.isInFrustum = function (target) {
  22634. this.updateFrustumPlanes();
  22635. return target.isInFrustum(this._frustumPlanes);
  22636. };
  22637. Camera.prototype.isCompletelyInFrustum = function (target) {
  22638. this.updateFrustumPlanes();
  22639. return target.isCompletelyInFrustum(this._frustumPlanes);
  22640. };
  22641. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22642. if (length === void 0) { length = 100; }
  22643. if (!transform) {
  22644. transform = this.getWorldMatrix();
  22645. }
  22646. if (!origin) {
  22647. origin = this.position;
  22648. }
  22649. var forward = new BABYLON.Vector3(0, 0, 1);
  22650. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22651. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22652. return new BABYLON.Ray(origin, direction, length);
  22653. };
  22654. /**
  22655. * Releases resources associated with this node.
  22656. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22657. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22658. */
  22659. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22660. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22661. // Observables
  22662. this.onViewMatrixChangedObservable.clear();
  22663. this.onProjectionMatrixChangedObservable.clear();
  22664. this.onAfterCheckInputsObservable.clear();
  22665. this.onRestoreStateObservable.clear();
  22666. // Inputs
  22667. if (this.inputs) {
  22668. this.inputs.clear();
  22669. }
  22670. // Animations
  22671. this.getScene().stopAnimation(this);
  22672. // Remove from scene
  22673. this.getScene().removeCamera(this);
  22674. while (this._rigCameras.length > 0) {
  22675. var camera = this._rigCameras.pop();
  22676. if (camera) {
  22677. camera.dispose();
  22678. }
  22679. }
  22680. // Postprocesses
  22681. if (this._rigPostProcess) {
  22682. this._rigPostProcess.dispose(this);
  22683. this._rigPostProcess = null;
  22684. this._postProcesses = [];
  22685. }
  22686. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22687. this._rigPostProcess = null;
  22688. this._postProcesses = [];
  22689. }
  22690. else {
  22691. var i = this._postProcesses.length;
  22692. while (--i >= 0) {
  22693. var postProcess = this._postProcesses[i];
  22694. if (postProcess) {
  22695. postProcess.dispose(this);
  22696. }
  22697. }
  22698. }
  22699. // Render targets
  22700. var i = this.customRenderTargets.length;
  22701. while (--i >= 0) {
  22702. this.customRenderTargets[i].dispose();
  22703. }
  22704. this.customRenderTargets = [];
  22705. // Active Meshes
  22706. this._activeMeshes.dispose();
  22707. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22708. };
  22709. Object.defineProperty(Camera.prototype, "leftCamera", {
  22710. // ---- Camera rigs section ----
  22711. get: function () {
  22712. if (this._rigCameras.length < 1) {
  22713. return null;
  22714. }
  22715. return this._rigCameras[0];
  22716. },
  22717. enumerable: true,
  22718. configurable: true
  22719. });
  22720. Object.defineProperty(Camera.prototype, "rightCamera", {
  22721. get: function () {
  22722. if (this._rigCameras.length < 2) {
  22723. return null;
  22724. }
  22725. return this._rigCameras[1];
  22726. },
  22727. enumerable: true,
  22728. configurable: true
  22729. });
  22730. Camera.prototype.getLeftTarget = function () {
  22731. if (this._rigCameras.length < 1) {
  22732. return null;
  22733. }
  22734. return this._rigCameras[0].getTarget();
  22735. };
  22736. Camera.prototype.getRightTarget = function () {
  22737. if (this._rigCameras.length < 2) {
  22738. return null;
  22739. }
  22740. return this._rigCameras[1].getTarget();
  22741. };
  22742. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22743. if (this.cameraRigMode === mode) {
  22744. return;
  22745. }
  22746. while (this._rigCameras.length > 0) {
  22747. var camera = this._rigCameras.pop();
  22748. if (camera) {
  22749. camera.dispose();
  22750. }
  22751. }
  22752. this.cameraRigMode = mode;
  22753. this._cameraRigParams = {};
  22754. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22755. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22756. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22757. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22758. // create the rig cameras, unless none
  22759. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22760. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22761. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22762. if (leftCamera && rightCamera) {
  22763. this._rigCameras.push(leftCamera);
  22764. this._rigCameras.push(rightCamera);
  22765. }
  22766. }
  22767. switch (this.cameraRigMode) {
  22768. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22769. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22770. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22771. break;
  22772. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22773. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22774. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22775. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22776. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22777. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22778. break;
  22779. case Camera.RIG_MODE_VR:
  22780. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22781. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22782. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22783. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22784. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22785. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22786. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22787. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22788. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22789. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22790. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22791. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22792. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22793. if (metrics.compensateDistortion) {
  22794. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22795. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22796. }
  22797. break;
  22798. case Camera.RIG_MODE_WEBVR:
  22799. if (rigParams.vrDisplay) {
  22800. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22801. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22802. //Left eye
  22803. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22804. this._rigCameras[0].setCameraRigParameter("left", true);
  22805. //leaving this for future reference
  22806. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22807. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22808. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22809. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22810. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22811. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22812. this._rigCameras[0].parent = this;
  22813. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22814. //Right eye
  22815. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22816. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22817. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22818. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22819. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22820. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22821. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22822. this._rigCameras[1].parent = this;
  22823. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22824. if (Camera.UseAlternateWebVRRendering) {
  22825. this._rigCameras[1]._skipRendering = true;
  22826. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22827. }
  22828. }
  22829. break;
  22830. }
  22831. this._cascadePostProcessesToRigCams();
  22832. this.update();
  22833. };
  22834. Camera.prototype._getVRProjectionMatrix = function () {
  22835. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22836. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22837. return this._projectionMatrix;
  22838. };
  22839. Camera.prototype._updateCameraRotationMatrix = function () {
  22840. //Here for WebVR
  22841. };
  22842. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22843. //Here for WebVR
  22844. };
  22845. /**
  22846. * This function MUST be overwritten by the different WebVR cameras available.
  22847. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22848. */
  22849. Camera.prototype._getWebVRProjectionMatrix = function () {
  22850. return BABYLON.Matrix.Identity();
  22851. };
  22852. /**
  22853. * This function MUST be overwritten by the different WebVR cameras available.
  22854. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22855. */
  22856. Camera.prototype._getWebVRViewMatrix = function () {
  22857. return BABYLON.Matrix.Identity();
  22858. };
  22859. Camera.prototype.setCameraRigParameter = function (name, value) {
  22860. if (!this._cameraRigParams) {
  22861. this._cameraRigParams = {};
  22862. }
  22863. this._cameraRigParams[name] = value;
  22864. //provisionnally:
  22865. if (name === "interaxialDistance") {
  22866. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22867. }
  22868. };
  22869. /**
  22870. * needs to be overridden by children so sub has required properties to be copied
  22871. */
  22872. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22873. return null;
  22874. };
  22875. /**
  22876. * May need to be overridden by children
  22877. * @hidden
  22878. */
  22879. Camera.prototype._updateRigCameras = function () {
  22880. for (var i = 0; i < this._rigCameras.length; i++) {
  22881. this._rigCameras[i].minZ = this.minZ;
  22882. this._rigCameras[i].maxZ = this.maxZ;
  22883. this._rigCameras[i].fov = this.fov;
  22884. }
  22885. // only update viewport when ANAGLYPH
  22886. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22887. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22888. }
  22889. };
  22890. /** @hidden */
  22891. Camera.prototype._setupInputs = function () {
  22892. };
  22893. Camera.prototype.serialize = function () {
  22894. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22895. // Type
  22896. serializationObject.type = this.getClassName();
  22897. // Parent
  22898. if (this.parent) {
  22899. serializationObject.parentId = this.parent.id;
  22900. }
  22901. if (this.inputs) {
  22902. this.inputs.serialize(serializationObject);
  22903. }
  22904. // Animations
  22905. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22906. serializationObject.ranges = this.serializeAnimationRanges();
  22907. return serializationObject;
  22908. };
  22909. Camera.prototype.clone = function (name) {
  22910. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22911. };
  22912. Camera.prototype.getDirection = function (localAxis) {
  22913. var result = BABYLON.Vector3.Zero();
  22914. this.getDirectionToRef(localAxis, result);
  22915. return result;
  22916. };
  22917. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22918. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22919. };
  22920. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22921. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22922. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22923. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22924. interaxial_distance: interaxial_distance,
  22925. isStereoscopicSideBySide: isStereoscopicSideBySide
  22926. });
  22927. if (constructorFunc) {
  22928. return constructorFunc;
  22929. }
  22930. // Default to universal camera
  22931. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22932. };
  22933. Camera.prototype.computeWorldMatrix = function () {
  22934. return this.getWorldMatrix();
  22935. };
  22936. Camera.Parse = function (parsedCamera, scene) {
  22937. var type = parsedCamera.type;
  22938. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22939. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22940. // Parent
  22941. if (parsedCamera.parentId) {
  22942. camera._waitingParentId = parsedCamera.parentId;
  22943. }
  22944. //If camera has an input manager, let it parse inputs settings
  22945. if (camera.inputs) {
  22946. camera.inputs.parse(parsedCamera);
  22947. camera._setupInputs();
  22948. }
  22949. if (camera.setPosition) { // need to force position
  22950. camera.position.copyFromFloats(0, 0, 0);
  22951. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22952. }
  22953. // Target
  22954. if (parsedCamera.target) {
  22955. if (camera.setTarget) {
  22956. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22957. }
  22958. }
  22959. // Apply 3d rig, when found
  22960. if (parsedCamera.cameraRigMode) {
  22961. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22962. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22963. }
  22964. // Animations
  22965. if (parsedCamera.animations) {
  22966. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22967. var parsedAnimation = parsedCamera.animations[animationIndex];
  22968. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22969. }
  22970. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22971. }
  22972. if (parsedCamera.autoAnimate) {
  22973. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22974. }
  22975. return camera;
  22976. };
  22977. // Statics
  22978. Camera._PERSPECTIVE_CAMERA = 0;
  22979. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22980. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22981. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22982. Camera._RIG_MODE_NONE = 0;
  22983. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22984. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22985. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22986. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22987. Camera._RIG_MODE_VR = 20;
  22988. Camera._RIG_MODE_WEBVR = 21;
  22989. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22990. Camera.UseAlternateWebVRRendering = false;
  22991. __decorate([
  22992. BABYLON.serializeAsVector3()
  22993. ], Camera.prototype, "position", void 0);
  22994. __decorate([
  22995. BABYLON.serializeAsVector3()
  22996. ], Camera.prototype, "upVector", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Camera.prototype, "orthoLeft", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "orthoRight", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "orthoBottom", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "orthoTop", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "fov", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "minZ", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "maxZ", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "inertia", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Camera.prototype, "mode", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Camera.prototype, "layerMask", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Camera.prototype, "fovMode", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Camera.prototype, "cameraRigMode", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Camera.prototype, "interaxialDistance", void 0);
  23036. __decorate([
  23037. BABYLON.serialize()
  23038. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23039. return Camera;
  23040. }(BABYLON.Node));
  23041. BABYLON.Camera = Camera;
  23042. })(BABYLON || (BABYLON = {}));
  23043. //# sourceMappingURL=babylon.camera.js.map
  23044. var BABYLON;
  23045. (function (BABYLON) {
  23046. var RenderingManager = /** @class */ (function () {
  23047. function RenderingManager(scene) {
  23048. /**
  23049. * @hidden
  23050. */
  23051. this._useSceneAutoClearSetup = false;
  23052. this._renderingGroups = new Array();
  23053. this._autoClearDepthStencil = {};
  23054. this._customOpaqueSortCompareFn = {};
  23055. this._customAlphaTestSortCompareFn = {};
  23056. this._customTransparentSortCompareFn = {};
  23057. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23058. this._scene = scene;
  23059. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23060. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23061. }
  23062. }
  23063. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23064. if (depth === void 0) { depth = true; }
  23065. if (stencil === void 0) { stencil = true; }
  23066. if (this._depthStencilBufferAlreadyCleaned) {
  23067. return;
  23068. }
  23069. this._scene.getEngine().clear(null, false, depth, stencil);
  23070. this._depthStencilBufferAlreadyCleaned = true;
  23071. };
  23072. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23073. // Update the observable context (not null as it only goes away on dispose)
  23074. var info = this._renderingGroupInfo;
  23075. info.scene = this._scene;
  23076. info.camera = this._scene.activeCamera;
  23077. // Dispatch sprites
  23078. if (this._scene.spriteManagers && renderSprites) {
  23079. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23080. var manager = this._scene.spriteManagers[index];
  23081. this.dispatchSprites(manager);
  23082. }
  23083. }
  23084. // Render
  23085. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23086. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23087. var renderingGroup = this._renderingGroups[index];
  23088. if (!renderingGroup)
  23089. continue;
  23090. var renderingGroupMask = Math.pow(2, index);
  23091. info.renderingGroupId = index;
  23092. // Before Observable
  23093. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23094. // Clear depth/stencil if needed
  23095. if (RenderingManager.AUTOCLEAR) {
  23096. var autoClear = this._useSceneAutoClearSetup ?
  23097. this._scene.getAutoClearDepthStencilSetup(index) :
  23098. this._autoClearDepthStencil[index];
  23099. if (autoClear && autoClear.autoClear) {
  23100. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23101. }
  23102. }
  23103. // Render
  23104. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23105. var step = _a[_i];
  23106. step.action(index);
  23107. }
  23108. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23109. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23110. var step = _c[_b];
  23111. step.action(index);
  23112. }
  23113. // After Observable
  23114. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23115. }
  23116. };
  23117. RenderingManager.prototype.reset = function () {
  23118. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23119. var renderingGroup = this._renderingGroups[index];
  23120. if (renderingGroup) {
  23121. renderingGroup.prepare();
  23122. }
  23123. }
  23124. };
  23125. RenderingManager.prototype.dispose = function () {
  23126. this.freeRenderingGroups();
  23127. this._renderingGroups.length = 0;
  23128. this._renderingGroupInfo = null;
  23129. };
  23130. /**
  23131. * Clear the info related to rendering groups preventing retention points during dispose.
  23132. */
  23133. RenderingManager.prototype.freeRenderingGroups = function () {
  23134. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23135. var renderingGroup = this._renderingGroups[index];
  23136. if (renderingGroup) {
  23137. renderingGroup.dispose();
  23138. }
  23139. }
  23140. };
  23141. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23142. if (this._renderingGroups[renderingGroupId] === undefined) {
  23143. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23144. }
  23145. };
  23146. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23147. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23148. this._prepareRenderingGroup(renderingGroupId);
  23149. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23150. };
  23151. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23152. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23153. this._prepareRenderingGroup(renderingGroupId);
  23154. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23155. };
  23156. /**
  23157. * @param subMesh The submesh to dispatch
  23158. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23159. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23160. */
  23161. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23162. if (mesh === undefined) {
  23163. mesh = subMesh.getMesh();
  23164. }
  23165. var renderingGroupId = mesh.renderingGroupId || 0;
  23166. this._prepareRenderingGroup(renderingGroupId);
  23167. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23168. };
  23169. /**
  23170. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23171. * This allowed control for front to back rendering or reversly depending of the special needs.
  23172. *
  23173. * @param renderingGroupId The rendering group id corresponding to its index
  23174. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23175. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23176. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23177. */
  23178. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23179. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23180. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23181. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23182. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23183. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23184. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23185. if (this._renderingGroups[renderingGroupId]) {
  23186. var group = this._renderingGroups[renderingGroupId];
  23187. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23188. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23189. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23190. }
  23191. };
  23192. /**
  23193. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23194. *
  23195. * @param renderingGroupId The rendering group id corresponding to its index
  23196. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23197. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23198. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23199. */
  23200. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23201. if (depth === void 0) { depth = true; }
  23202. if (stencil === void 0) { stencil = true; }
  23203. this._autoClearDepthStencil[renderingGroupId] = {
  23204. autoClear: autoClearDepthStencil,
  23205. depth: depth,
  23206. stencil: stencil
  23207. };
  23208. };
  23209. /**
  23210. * Gets the current auto clear configuration for one rendering group of the rendering
  23211. * manager.
  23212. * @param index the rendering group index to get the information for
  23213. * @returns The auto clear setup for the requested rendering group
  23214. */
  23215. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23216. return this._autoClearDepthStencil[index];
  23217. };
  23218. /**
  23219. * The max id used for rendering groups (not included)
  23220. */
  23221. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23222. /**
  23223. * The min id used for rendering groups (included)
  23224. */
  23225. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23226. /**
  23227. * Used to globally prevent autoclearing scenes.
  23228. */
  23229. RenderingManager.AUTOCLEAR = true;
  23230. return RenderingManager;
  23231. }());
  23232. BABYLON.RenderingManager = RenderingManager;
  23233. })(BABYLON || (BABYLON = {}));
  23234. //# sourceMappingURL=babylon.renderingManager.js.map
  23235. var BABYLON;
  23236. (function (BABYLON) {
  23237. var RenderingGroup = /** @class */ (function () {
  23238. /**
  23239. * Creates a new rendering group.
  23240. * @param index The rendering group index
  23241. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23242. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23243. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23244. */
  23245. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23246. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23247. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23248. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23249. this.index = index;
  23250. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23251. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23252. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23253. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23254. this._particleSystems = new BABYLON.SmartArray(256);
  23255. this._spriteManagers = new BABYLON.SmartArray(256);
  23256. this._edgesRenderers = new BABYLON.SmartArray(16);
  23257. this._scene = scene;
  23258. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23259. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23260. this.transparentSortCompareFn = transparentSortCompareFn;
  23261. }
  23262. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23263. /**
  23264. * Set the opaque sort comparison function.
  23265. * If null the sub meshes will be render in the order they were created
  23266. */
  23267. set: function (value) {
  23268. this._opaqueSortCompareFn = value;
  23269. if (value) {
  23270. this._renderOpaque = this.renderOpaqueSorted;
  23271. }
  23272. else {
  23273. this._renderOpaque = RenderingGroup.renderUnsorted;
  23274. }
  23275. },
  23276. enumerable: true,
  23277. configurable: true
  23278. });
  23279. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23280. /**
  23281. * Set the alpha test sort comparison function.
  23282. * If null the sub meshes will be render in the order they were created
  23283. */
  23284. set: function (value) {
  23285. this._alphaTestSortCompareFn = value;
  23286. if (value) {
  23287. this._renderAlphaTest = this.renderAlphaTestSorted;
  23288. }
  23289. else {
  23290. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23291. }
  23292. },
  23293. enumerable: true,
  23294. configurable: true
  23295. });
  23296. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23297. /**
  23298. * Set the transparent sort comparison function.
  23299. * If null the sub meshes will be render in the order they were created
  23300. */
  23301. set: function (value) {
  23302. if (value) {
  23303. this._transparentSortCompareFn = value;
  23304. }
  23305. else {
  23306. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23307. }
  23308. this._renderTransparent = this.renderTransparentSorted;
  23309. },
  23310. enumerable: true,
  23311. configurable: true
  23312. });
  23313. /**
  23314. * Render all the sub meshes contained in the group.
  23315. * @param customRenderFunction Used to override the default render behaviour of the group.
  23316. * @returns true if rendered some submeshes.
  23317. */
  23318. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23319. if (customRenderFunction) {
  23320. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23321. return;
  23322. }
  23323. var engine = this._scene.getEngine();
  23324. // Depth only
  23325. if (this._depthOnlySubMeshes.length !== 0) {
  23326. engine.setColorWrite(false);
  23327. this._renderAlphaTest(this._depthOnlySubMeshes);
  23328. engine.setColorWrite(true);
  23329. }
  23330. // Opaque
  23331. if (this._opaqueSubMeshes.length !== 0) {
  23332. this._renderOpaque(this._opaqueSubMeshes);
  23333. }
  23334. // Alpha test
  23335. if (this._alphaTestSubMeshes.length !== 0) {
  23336. this._renderAlphaTest(this._alphaTestSubMeshes);
  23337. }
  23338. var stencilState = engine.getStencilBuffer();
  23339. engine.setStencilBuffer(false);
  23340. // Sprites
  23341. if (renderSprites) {
  23342. this._renderSprites();
  23343. }
  23344. // Particles
  23345. if (renderParticles) {
  23346. this._renderParticles(activeMeshes);
  23347. }
  23348. if (this.onBeforeTransparentRendering) {
  23349. this.onBeforeTransparentRendering();
  23350. }
  23351. // Transparent
  23352. if (this._transparentSubMeshes.length !== 0) {
  23353. this._renderTransparent(this._transparentSubMeshes);
  23354. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23355. }
  23356. // Set back stencil to false in case it changes before the edge renderer.
  23357. engine.setStencilBuffer(false);
  23358. // Edges
  23359. if (this._edgesRenderers.length) {
  23360. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23361. this._edgesRenderers.data[edgesRendererIndex].render();
  23362. }
  23363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23364. }
  23365. // Restore Stencil state.
  23366. engine.setStencilBuffer(stencilState);
  23367. };
  23368. /**
  23369. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23370. * @param subMeshes The submeshes to render
  23371. */
  23372. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23373. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23374. };
  23375. /**
  23376. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23377. * @param subMeshes The submeshes to render
  23378. */
  23379. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23380. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23381. };
  23382. /**
  23383. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23384. * @param subMeshes The submeshes to render
  23385. */
  23386. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23387. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23388. };
  23389. /**
  23390. * Renders the submeshes in a specified order.
  23391. * @param subMeshes The submeshes to sort before render
  23392. * @param sortCompareFn The comparison function use to sort
  23393. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23394. * @param transparent Specifies to activate blending if true
  23395. */
  23396. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23397. var subIndex = 0;
  23398. var subMesh;
  23399. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23400. for (; subIndex < subMeshes.length; subIndex++) {
  23401. subMesh = subMeshes.data[subIndex];
  23402. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23403. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23404. }
  23405. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23406. if (sortCompareFn) {
  23407. sortedArray.sort(sortCompareFn);
  23408. }
  23409. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23410. subMesh = sortedArray[subIndex];
  23411. if (transparent) {
  23412. var material = subMesh.getMaterial();
  23413. if (material && material.needDepthPrePass) {
  23414. var engine = material.getScene().getEngine();
  23415. engine.setColorWrite(false);
  23416. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23417. subMesh.render(false);
  23418. engine.setColorWrite(true);
  23419. }
  23420. }
  23421. subMesh.render(transparent);
  23422. }
  23423. };
  23424. /**
  23425. * Renders the submeshes in the order they were dispatched (no sort applied).
  23426. * @param subMeshes The submeshes to render
  23427. */
  23428. RenderingGroup.renderUnsorted = function (subMeshes) {
  23429. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23430. var submesh = subMeshes.data[subIndex];
  23431. submesh.render(false);
  23432. }
  23433. };
  23434. /**
  23435. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23436. * are rendered back to front if in the same alpha index.
  23437. *
  23438. * @param a The first submesh
  23439. * @param b The second submesh
  23440. * @returns The result of the comparison
  23441. */
  23442. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23443. // Alpha index first
  23444. if (a._alphaIndex > b._alphaIndex) {
  23445. return 1;
  23446. }
  23447. if (a._alphaIndex < b._alphaIndex) {
  23448. return -1;
  23449. }
  23450. // Then distance to camera
  23451. return RenderingGroup.backToFrontSortCompare(a, b);
  23452. };
  23453. /**
  23454. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23455. * are rendered back to front.
  23456. *
  23457. * @param a The first submesh
  23458. * @param b The second submesh
  23459. * @returns The result of the comparison
  23460. */
  23461. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23462. // Then distance to camera
  23463. if (a._distanceToCamera < b._distanceToCamera) {
  23464. return 1;
  23465. }
  23466. if (a._distanceToCamera > b._distanceToCamera) {
  23467. return -1;
  23468. }
  23469. return 0;
  23470. };
  23471. /**
  23472. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23473. * are rendered front to back (prevent overdraw).
  23474. *
  23475. * @param a The first submesh
  23476. * @param b The second submesh
  23477. * @returns The result of the comparison
  23478. */
  23479. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23480. // Then distance to camera
  23481. if (a._distanceToCamera < b._distanceToCamera) {
  23482. return -1;
  23483. }
  23484. if (a._distanceToCamera > b._distanceToCamera) {
  23485. return 1;
  23486. }
  23487. return 0;
  23488. };
  23489. /**
  23490. * Resets the different lists of submeshes to prepare a new frame.
  23491. */
  23492. RenderingGroup.prototype.prepare = function () {
  23493. this._opaqueSubMeshes.reset();
  23494. this._transparentSubMeshes.reset();
  23495. this._alphaTestSubMeshes.reset();
  23496. this._depthOnlySubMeshes.reset();
  23497. this._particleSystems.reset();
  23498. this._spriteManagers.reset();
  23499. this._edgesRenderers.reset();
  23500. };
  23501. RenderingGroup.prototype.dispose = function () {
  23502. this._opaqueSubMeshes.dispose();
  23503. this._transparentSubMeshes.dispose();
  23504. this._alphaTestSubMeshes.dispose();
  23505. this._depthOnlySubMeshes.dispose();
  23506. this._particleSystems.dispose();
  23507. this._spriteManagers.dispose();
  23508. this._edgesRenderers.dispose();
  23509. };
  23510. /**
  23511. * Inserts the submesh in its correct queue depending on its material.
  23512. * @param subMesh The submesh to dispatch
  23513. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23514. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23515. */
  23516. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23517. // Get mesh and materials if not provided
  23518. if (mesh === undefined) {
  23519. mesh = subMesh.getMesh();
  23520. }
  23521. if (material === undefined) {
  23522. material = subMesh.getMaterial();
  23523. }
  23524. if (material === null || material === undefined) {
  23525. return;
  23526. }
  23527. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23528. this._transparentSubMeshes.push(subMesh);
  23529. }
  23530. else if (material.needAlphaTesting()) { // Alpha test
  23531. if (material.needDepthPrePass) {
  23532. this._depthOnlySubMeshes.push(subMesh);
  23533. }
  23534. this._alphaTestSubMeshes.push(subMesh);
  23535. }
  23536. else {
  23537. if (material.needDepthPrePass) {
  23538. this._depthOnlySubMeshes.push(subMesh);
  23539. }
  23540. this._opaqueSubMeshes.push(subMesh); // Opaque
  23541. }
  23542. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23543. this._edgesRenderers.push(mesh._edgesRenderer);
  23544. }
  23545. };
  23546. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23547. this._spriteManagers.push(spriteManager);
  23548. };
  23549. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23550. this._particleSystems.push(particleSystem);
  23551. };
  23552. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23553. if (this._particleSystems.length === 0) {
  23554. return;
  23555. }
  23556. // Particles
  23557. var activeCamera = this._scene.activeCamera;
  23558. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23559. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23560. var particleSystem = this._particleSystems.data[particleIndex];
  23561. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23562. continue;
  23563. }
  23564. var emitter = particleSystem.emitter;
  23565. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23566. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23567. }
  23568. }
  23569. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23570. };
  23571. RenderingGroup.prototype._renderSprites = function () {
  23572. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23573. return;
  23574. }
  23575. // Sprites
  23576. var activeCamera = this._scene.activeCamera;
  23577. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23578. for (var id = 0; id < this._spriteManagers.length; id++) {
  23579. var spriteManager = this._spriteManagers.data[id];
  23580. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23581. spriteManager.render();
  23582. }
  23583. }
  23584. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23585. };
  23586. return RenderingGroup;
  23587. }());
  23588. BABYLON.RenderingGroup = RenderingGroup;
  23589. })(BABYLON || (BABYLON = {}));
  23590. //# sourceMappingURL=babylon.renderingGroup.js.map
  23591. var BABYLON;
  23592. (function (BABYLON) {
  23593. /**
  23594. * Groups all the scene component constants in one place to ease maintenance.
  23595. * @hidden
  23596. */
  23597. var SceneComponentConstants = /** @class */ (function () {
  23598. function SceneComponentConstants() {
  23599. }
  23600. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23601. SceneComponentConstants.NAME_LAYER = "Layer";
  23602. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23603. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23604. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23605. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23606. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23607. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23608. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23609. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23610. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23611. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23612. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23613. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23614. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23615. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23616. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23617. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23618. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23619. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23620. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23621. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23622. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23623. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23624. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23625. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23626. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23627. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23628. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23629. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23630. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23631. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23632. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23633. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23634. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23635. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23636. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23637. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23638. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23639. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23640. return SceneComponentConstants;
  23641. }());
  23642. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23643. /**
  23644. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23645. * @hidden
  23646. */
  23647. var Stage = /** @class */ (function (_super) {
  23648. __extends(Stage, _super);
  23649. /**
  23650. * Hide ctor from the rest of the world.
  23651. * @param items The items to add.
  23652. */
  23653. function Stage(items) {
  23654. return _super.apply(this, items) || this;
  23655. }
  23656. /**
  23657. * Creates a new Stage.
  23658. * @returns A new instance of a Stage
  23659. */
  23660. Stage.Create = function () {
  23661. return Object.create(Stage.prototype);
  23662. };
  23663. /**
  23664. * Registers a step in an ordered way in the targeted stage.
  23665. * @param index Defines the position to register the step in
  23666. * @param component Defines the component attached to the step
  23667. * @param action Defines the action to launch during the step
  23668. */
  23669. Stage.prototype.registerStep = function (index, component, action) {
  23670. var i = 0;
  23671. var maxIndex = Number.MAX_VALUE;
  23672. for (; i < this.length && i < maxIndex; i++) {
  23673. var step = this[i];
  23674. maxIndex = step.index;
  23675. }
  23676. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23677. };
  23678. /**
  23679. * Clears all the steps from the stage.
  23680. */
  23681. Stage.prototype.clear = function () {
  23682. this.length = 0;
  23683. };
  23684. return Stage;
  23685. }(Array));
  23686. BABYLON.Stage = Stage;
  23687. })(BABYLON || (BABYLON = {}));
  23688. //# sourceMappingURL=babylon.sceneComponent.js.map
  23689. var BABYLON;
  23690. (function (BABYLON) {
  23691. /**
  23692. * Base class of the scene acting as a container for the different elements composing a scene.
  23693. * This class is dynamically extended by the different components of the scene increasing
  23694. * flexibility and reducing coupling
  23695. */
  23696. var AbstractScene = /** @class */ (function () {
  23697. function AbstractScene() {
  23698. /** All of the cameras added to this scene
  23699. * @see http://doc.babylonjs.com/babylon101/cameras
  23700. */
  23701. this.cameras = new Array();
  23702. /**
  23703. * All of the lights added to this scene
  23704. * @see http://doc.babylonjs.com/babylon101/lights
  23705. */
  23706. this.lights = new Array();
  23707. /**
  23708. * All of the (abstract) meshes added to this scene
  23709. */
  23710. this.meshes = new Array();
  23711. /**
  23712. * The list of skeletons added to the scene
  23713. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23714. */
  23715. this.skeletons = new Array();
  23716. /**
  23717. * All of the particle systems added to this scene
  23718. * @see http://doc.babylonjs.com/babylon101/particles
  23719. */
  23720. this.particleSystems = new Array();
  23721. /**
  23722. * Gets a list of Animations associated with the scene
  23723. */
  23724. this.animations = [];
  23725. /**
  23726. * All of the animation groups added to this scene
  23727. * @see http://doc.babylonjs.com/how_to/group
  23728. */
  23729. this.animationGroups = new Array();
  23730. /**
  23731. * All of the multi-materials added to this scene
  23732. * @see http://doc.babylonjs.com/how_to/multi_materials
  23733. */
  23734. this.multiMaterials = new Array();
  23735. /**
  23736. * All of the materials added to this scene
  23737. * @see http://doc.babylonjs.com/babylon101/materials
  23738. */
  23739. this.materials = new Array();
  23740. /**
  23741. * The list of morph target managers added to the scene
  23742. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23743. */
  23744. this.morphTargetManagers = new Array();
  23745. /**
  23746. * The list of geometries used in the scene.
  23747. */
  23748. this.geometries = new Array();
  23749. /**
  23750. * All of the tranform nodes added to this scene
  23751. * @see http://doc.babylonjs.com/how_to/transformnode
  23752. */
  23753. this.transformNodes = new Array();
  23754. /**
  23755. * ActionManagers available on the scene.
  23756. */
  23757. this.actionManagers = new Array();
  23758. /**
  23759. * Sounds to keep.
  23760. */
  23761. this.sounds = new Array();
  23762. /**
  23763. * Textures to keep.
  23764. */
  23765. this.textures = new Array();
  23766. }
  23767. /**
  23768. * Adds a parser in the list of available ones
  23769. * @param name Defines the name of the parser
  23770. * @param parser Defines the parser to add
  23771. */
  23772. AbstractScene.AddParser = function (name, parser) {
  23773. this._BabylonFileParsers[name] = parser;
  23774. };
  23775. /**
  23776. * Gets a general parser from the list of avaialble ones
  23777. * @param name Defines the name of the parser
  23778. * @returns the requested parser or null
  23779. */
  23780. AbstractScene.GetParser = function (name) {
  23781. if (this._BabylonFileParsers[name]) {
  23782. return this._BabylonFileParsers[name];
  23783. }
  23784. return null;
  23785. };
  23786. /**
  23787. * Adds n individual parser in the list of available ones
  23788. * @param name Defines the name of the parser
  23789. * @param parser Defines the parser to add
  23790. */
  23791. AbstractScene.AddIndividualParser = function (name, parser) {
  23792. this._IndividualBabylonFileParsers[name] = parser;
  23793. };
  23794. /**
  23795. * Gets an individual parser from the list of avaialble ones
  23796. * @param name Defines the name of the parser
  23797. * @returns the requested parser or null
  23798. */
  23799. AbstractScene.GetIndividualParser = function (name) {
  23800. if (this._IndividualBabylonFileParsers[name]) {
  23801. return this._IndividualBabylonFileParsers[name];
  23802. }
  23803. return null;
  23804. };
  23805. /**
  23806. * Parser json data and populate both a scene and its associated container object
  23807. * @param jsonData Defines the data to parse
  23808. * @param scene Defines the scene to parse the data for
  23809. * @param container Defines the container attached to the parsing sequence
  23810. * @param rootUrl Defines the root url of the data
  23811. */
  23812. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23813. for (var parserName in this._BabylonFileParsers) {
  23814. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23815. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23816. }
  23817. }
  23818. };
  23819. /**
  23820. * Stores the list of available parsers in the application.
  23821. */
  23822. AbstractScene._BabylonFileParsers = {};
  23823. /**
  23824. * Stores the list of available individual parsers in the application.
  23825. */
  23826. AbstractScene._IndividualBabylonFileParsers = {};
  23827. return AbstractScene;
  23828. }());
  23829. BABYLON.AbstractScene = AbstractScene;
  23830. })(BABYLON || (BABYLON = {}));
  23831. //# sourceMappingURL=babylon.abstractScene.js.map
  23832. var BABYLON;
  23833. (function (BABYLON) {
  23834. /** @hidden */
  23835. var ClickInfo = /** @class */ (function () {
  23836. function ClickInfo() {
  23837. this._singleClick = false;
  23838. this._doubleClick = false;
  23839. this._hasSwiped = false;
  23840. this._ignore = false;
  23841. }
  23842. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23843. get: function () {
  23844. return this._singleClick;
  23845. },
  23846. set: function (b) {
  23847. this._singleClick = b;
  23848. },
  23849. enumerable: true,
  23850. configurable: true
  23851. });
  23852. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23853. get: function () {
  23854. return this._doubleClick;
  23855. },
  23856. set: function (b) {
  23857. this._doubleClick = b;
  23858. },
  23859. enumerable: true,
  23860. configurable: true
  23861. });
  23862. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23863. get: function () {
  23864. return this._hasSwiped;
  23865. },
  23866. set: function (b) {
  23867. this._hasSwiped = b;
  23868. },
  23869. enumerable: true,
  23870. configurable: true
  23871. });
  23872. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23873. get: function () {
  23874. return this._ignore;
  23875. },
  23876. set: function (b) {
  23877. this._ignore = b;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. return ClickInfo;
  23883. }());
  23884. /**
  23885. * This class is used by the onRenderingGroupObservable
  23886. */
  23887. var RenderingGroupInfo = /** @class */ (function () {
  23888. function RenderingGroupInfo() {
  23889. }
  23890. return RenderingGroupInfo;
  23891. }());
  23892. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23893. /**
  23894. * Represents a scene to be rendered by the engine.
  23895. * @see http://doc.babylonjs.com/features/scene
  23896. */
  23897. var Scene = /** @class */ (function (_super) {
  23898. __extends(Scene, _super);
  23899. /**
  23900. * Creates a new Scene
  23901. * @param engine defines the engine to use to render this scene
  23902. */
  23903. function Scene(engine) {
  23904. var _this = _super.call(this) || this;
  23905. // Members
  23906. /**
  23907. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23908. */
  23909. _this.autoClear = true;
  23910. /**
  23911. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23912. */
  23913. _this.autoClearDepthAndStencil = true;
  23914. /**
  23915. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23916. */
  23917. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23918. /**
  23919. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23920. */
  23921. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23922. _this._forceWireframe = false;
  23923. _this._forcePointsCloud = false;
  23924. /**
  23925. * Gets or sets a boolean indicating if animations are enabled
  23926. */
  23927. _this.animationsEnabled = true;
  23928. _this._animationPropertiesOverride = null;
  23929. /**
  23930. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23931. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23932. */
  23933. _this.useConstantAnimationDeltaTime = false;
  23934. /**
  23935. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23936. * Please note that it requires to run a ray cast through the scene on every frame
  23937. */
  23938. _this.constantlyUpdateMeshUnderPointer = false;
  23939. /**
  23940. * Defines the HTML cursor to use when hovering over interactive elements
  23941. */
  23942. _this.hoverCursor = "pointer";
  23943. /**
  23944. * Defines the HTML default cursor to use (empty by default)
  23945. */
  23946. _this.defaultCursor = "";
  23947. /**
  23948. * This is used to call preventDefault() on pointer down
  23949. * in order to block unwanted artifacts like system double clicks
  23950. */
  23951. _this.preventDefaultOnPointerDown = true;
  23952. // Metadata
  23953. /**
  23954. * Gets or sets user defined metadata
  23955. */
  23956. _this.metadata = null;
  23957. /**
  23958. * Use this array to add regular expressions used to disable offline support for specific urls
  23959. */
  23960. _this.disableOfflineSupportExceptionRules = new Array();
  23961. /**
  23962. * An event triggered when the scene is disposed.
  23963. */
  23964. _this.onDisposeObservable = new BABYLON.Observable();
  23965. _this._onDisposeObserver = null;
  23966. /**
  23967. * An event triggered before rendering the scene (right after animations and physics)
  23968. */
  23969. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23970. _this._onBeforeRenderObserver = null;
  23971. /**
  23972. * An event triggered after rendering the scene
  23973. */
  23974. _this.onAfterRenderObservable = new BABYLON.Observable();
  23975. _this._onAfterRenderObserver = null;
  23976. /**
  23977. * An event triggered before animating the scene
  23978. */
  23979. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23980. /**
  23981. * An event triggered after animations processing
  23982. */
  23983. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23984. /**
  23985. * An event triggered before draw calls are ready to be sent
  23986. */
  23987. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23988. /**
  23989. * An event triggered after draw calls have been sent
  23990. */
  23991. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23992. /**
  23993. * An event triggered when physic simulation is about to be run
  23994. */
  23995. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23996. /**
  23997. * An event triggered when physic simulation has been done
  23998. */
  23999. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24000. /**
  24001. * An event triggered when the scene is ready
  24002. */
  24003. _this.onReadyObservable = new BABYLON.Observable();
  24004. /**
  24005. * An event triggered before rendering a camera
  24006. */
  24007. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24008. _this._onBeforeCameraRenderObserver = null;
  24009. /**
  24010. * An event triggered after rendering a camera
  24011. */
  24012. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24013. _this._onAfterCameraRenderObserver = null;
  24014. /**
  24015. * An event triggered when active meshes evaluation is about to start
  24016. */
  24017. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when active meshes evaluation is done
  24020. */
  24021. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered when particles rendering is about to start
  24024. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24025. */
  24026. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24027. /**
  24028. * An event triggered when particles rendering is done
  24029. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24030. */
  24031. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24032. /**
  24033. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24034. */
  24035. _this.onDataLoadedObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when a camera is created
  24038. */
  24039. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24040. /**
  24041. * An event triggered when a camera is removed
  24042. */
  24043. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24044. /**
  24045. * An event triggered when a light is created
  24046. */
  24047. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24048. /**
  24049. * An event triggered when a light is removed
  24050. */
  24051. _this.onLightRemovedObservable = new BABYLON.Observable();
  24052. /**
  24053. * An event triggered when a geometry is created
  24054. */
  24055. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24056. /**
  24057. * An event triggered when a geometry is removed
  24058. */
  24059. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24060. /**
  24061. * An event triggered when a transform node is created
  24062. */
  24063. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24064. /**
  24065. * An event triggered when a transform node is removed
  24066. */
  24067. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24068. /**
  24069. * An event triggered when a mesh is created
  24070. */
  24071. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24072. /**
  24073. * An event triggered when a mesh is removed
  24074. */
  24075. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24076. /**
  24077. * An event triggered when render targets are about to be rendered
  24078. * Can happen multiple times per frame.
  24079. */
  24080. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24081. /**
  24082. * An event triggered when render targets were rendered.
  24083. * Can happen multiple times per frame.
  24084. */
  24085. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24086. /**
  24087. * An event triggered before calculating deterministic simulation step
  24088. */
  24089. _this.onBeforeStepObservable = new BABYLON.Observable();
  24090. /**
  24091. * An event triggered after calculating deterministic simulation step
  24092. */
  24093. _this.onAfterStepObservable = new BABYLON.Observable();
  24094. /**
  24095. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24096. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24097. * 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)
  24098. */
  24099. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24100. /**
  24101. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24102. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24103. * 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)
  24104. */
  24105. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24106. // Animations
  24107. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24108. /**
  24109. * 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).
  24110. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24111. */
  24112. _this.onPrePointerObservable = new BABYLON.Observable();
  24113. /**
  24114. * Observable event triggered each time an input event is received from the rendering canvas
  24115. */
  24116. _this.onPointerObservable = new BABYLON.Observable();
  24117. _this._meshPickProceed = false;
  24118. _this._currentPickResult = null;
  24119. _this._previousPickResult = null;
  24120. _this._totalPointersPressed = 0;
  24121. _this._doubleClickOccured = false;
  24122. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24123. _this.cameraToUseForPointers = null;
  24124. _this._pointerX = 0;
  24125. _this._pointerY = 0;
  24126. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24127. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24128. _this._startingPointerTime = 0;
  24129. _this._previousStartingPointerTime = 0;
  24130. _this._pointerCaptures = {};
  24131. // Deterministic lockstep
  24132. _this._timeAccumulator = 0;
  24133. _this._currentStepId = 0;
  24134. _this._currentInternalStep = 0;
  24135. // Keyboard
  24136. /**
  24137. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24138. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24139. */
  24140. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24141. /**
  24142. * Observable event triggered each time an keyboard event is received from the hosting window
  24143. */
  24144. _this.onKeyboardObservable = new BABYLON.Observable();
  24145. // Coordinates system
  24146. _this._useRightHandedSystem = false;
  24147. // Fog
  24148. _this._fogEnabled = true;
  24149. _this._fogMode = Scene.FOGMODE_NONE;
  24150. /**
  24151. * Gets or sets the fog color to use
  24152. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24153. */
  24154. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24155. /**
  24156. * Gets or sets the fog density to use
  24157. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24158. */
  24159. _this.fogDensity = 0.1;
  24160. /**
  24161. * Gets or sets the fog start distance to use
  24162. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24163. */
  24164. _this.fogStart = 0;
  24165. /**
  24166. * Gets or sets the fog end distance to use
  24167. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24168. */
  24169. _this.fogEnd = 1000.0;
  24170. // Lights
  24171. _this._shadowsEnabled = true;
  24172. _this._lightsEnabled = true;
  24173. /** All of the active cameras added to this scene. */
  24174. _this.activeCameras = new Array();
  24175. // Textures
  24176. _this._texturesEnabled = true;
  24177. // Particles
  24178. /**
  24179. * Gets or sets a boolean indicating if particles are enabled on this scene
  24180. */
  24181. _this.particlesEnabled = true;
  24182. // Sprites
  24183. /**
  24184. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24185. */
  24186. _this.spritesEnabled = true;
  24187. // Skeletons
  24188. _this._skeletonsEnabled = true;
  24189. // Lens flares
  24190. /**
  24191. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24192. */
  24193. _this.lensFlaresEnabled = true;
  24194. // Collisions
  24195. /**
  24196. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24197. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24198. */
  24199. _this.collisionsEnabled = true;
  24200. /**
  24201. * Defines the gravity applied to this scene (used only for collisions)
  24202. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24203. */
  24204. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24205. // Postprocesses
  24206. /**
  24207. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24208. */
  24209. _this.postProcessesEnabled = true;
  24210. /**
  24211. * The list of postprocesses added to the scene
  24212. */
  24213. _this.postProcesses = new Array();
  24214. // Customs render targets
  24215. /**
  24216. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24217. */
  24218. _this.renderTargetsEnabled = true;
  24219. /**
  24220. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24221. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24222. */
  24223. _this.dumpNextRenderTargets = false;
  24224. /**
  24225. * The list of user defined render targets added to the scene
  24226. */
  24227. _this.customRenderTargets = new Array();
  24228. /**
  24229. * Gets the list of meshes imported to the scene through SceneLoader
  24230. */
  24231. _this.importedMeshesFiles = new Array();
  24232. // Probes
  24233. /**
  24234. * Gets or sets a boolean indicating if probes are enabled on this scene
  24235. */
  24236. _this.probesEnabled = true;
  24237. /**
  24238. * The list of reflection probes added to the scene
  24239. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24240. */
  24241. _this.reflectionProbes = new Array();
  24242. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24243. // Procedural textures
  24244. /**
  24245. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24246. */
  24247. _this.proceduralTexturesEnabled = true;
  24248. /**
  24249. * The list of sound tracks added to the scene
  24250. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24251. */
  24252. _this.soundTracks = new Array();
  24253. _this._audioEnabled = true;
  24254. _this._headphone = false;
  24255. // Performance counters
  24256. _this._totalVertices = new BABYLON.PerfCounter();
  24257. /** @hidden */
  24258. _this._activeIndices = new BABYLON.PerfCounter();
  24259. /** @hidden */
  24260. _this._activeParticles = new BABYLON.PerfCounter();
  24261. /** @hidden */
  24262. _this._activeBones = new BABYLON.PerfCounter();
  24263. _this._animationTime = 0;
  24264. /**
  24265. * Gets or sets a general scale for animation speed
  24266. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24267. */
  24268. _this.animationTimeScale = 1;
  24269. _this._renderId = 0;
  24270. _this._executeWhenReadyTimeoutId = -1;
  24271. _this._intermediateRendering = false;
  24272. _this._viewUpdateFlag = -1;
  24273. _this._projectionUpdateFlag = -1;
  24274. _this._alternateViewUpdateFlag = -1;
  24275. _this._alternateProjectionUpdateFlag = -1;
  24276. /** @hidden */
  24277. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24278. _this._activeRequests = new Array();
  24279. _this._pendingData = new Array();
  24280. _this._isDisposed = false;
  24281. /**
  24282. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24283. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24284. */
  24285. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24286. _this._activeMeshes = new BABYLON.SmartArray(256);
  24287. _this._processedMaterials = new BABYLON.SmartArray(256);
  24288. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24289. /** @hidden */
  24290. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24291. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24292. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24293. /** @hidden */
  24294. _this._activeAnimatables = new Array();
  24295. _this._transformMatrix = BABYLON.Matrix.Zero();
  24296. _this._useAlternateCameraConfiguration = false;
  24297. _this._alternateRendering = false;
  24298. /**
  24299. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24300. * This is useful if there are more lights that the maximum simulteanous authorized
  24301. */
  24302. _this.requireLightSorting = false;
  24303. /**
  24304. * @hidden
  24305. * Backing store of defined scene components.
  24306. */
  24307. _this._components = [];
  24308. /**
  24309. * @hidden
  24310. * Backing store of defined scene components.
  24311. */
  24312. _this._serializableComponents = [];
  24313. /**
  24314. * List of components to register on the next registration step.
  24315. */
  24316. _this._transientComponents = [];
  24317. /**
  24318. * @hidden
  24319. * Defines the actions happening before camera updates.
  24320. */
  24321. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24322. /**
  24323. * @hidden
  24324. * Defines the actions happening before clear the canvas.
  24325. */
  24326. _this._beforeClearStage = BABYLON.Stage.Create();
  24327. /**
  24328. * @hidden
  24329. * Defines the actions happening before camera updates.
  24330. */
  24331. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24332. /**
  24333. * @hidden
  24334. * Defines the actions happening during the per mesh ready checks.
  24335. */
  24336. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24337. /**
  24338. * @hidden
  24339. * Defines the actions happening before evaluate active mesh checks.
  24340. */
  24341. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24342. /**
  24343. * @hidden
  24344. * Defines the actions happening during the evaluate sub mesh checks.
  24345. */
  24346. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24347. /**
  24348. * @hidden
  24349. * Defines the actions happening during the active mesh stage.
  24350. */
  24351. _this._activeMeshStage = BABYLON.Stage.Create();
  24352. /**
  24353. * @hidden
  24354. * Defines the actions happening during the per camera render target step.
  24355. */
  24356. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24357. /**
  24358. * @hidden
  24359. * Defines the actions happening just before the active camera is drawing.
  24360. */
  24361. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24362. /**
  24363. * @hidden
  24364. * Defines the actions happening just before a rendering group is drawing.
  24365. */
  24366. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24367. /**
  24368. * @hidden
  24369. * Defines the actions happening just before a mesh is drawing.
  24370. */
  24371. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24372. /**
  24373. * @hidden
  24374. * Defines the actions happening just after a mesh has been drawn.
  24375. */
  24376. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24377. /**
  24378. * @hidden
  24379. * Defines the actions happening just after a rendering group has been drawn.
  24380. */
  24381. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24382. /**
  24383. * @hidden
  24384. * Defines the actions happening just after the active camera has been drawn.
  24385. */
  24386. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24387. /**
  24388. * @hidden
  24389. * Defines the actions happening when Geometries are rebuilding.
  24390. */
  24391. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24392. /**
  24393. * @hidden
  24394. * Defines the actions happening when a pointer move event happens.
  24395. */
  24396. _this._pointerMoveStage = BABYLON.Stage.Create();
  24397. /**
  24398. * @hidden
  24399. * Defines the actions happening when a pointer down event happens.
  24400. */
  24401. _this._pointerDownStage = BABYLON.Stage.Create();
  24402. /**
  24403. * @hidden
  24404. * Defines the actions happening when a pointer up event happens.
  24405. */
  24406. _this._pointerUpStage = BABYLON.Stage.Create();
  24407. _this._activeMeshesFrozen = false;
  24408. /** @hidden */
  24409. _this._allowPostProcessClearColor = true;
  24410. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24411. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24412. _this.blockMaterialDirtyMechanism = false;
  24413. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24414. _this._engine.scenes.push(_this);
  24415. _this._uid = null;
  24416. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24417. if (BABYLON.PostProcessManager) {
  24418. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24419. }
  24420. if (BABYLON.Tools.IsWindowObjectExist()) {
  24421. _this.attachControl();
  24422. }
  24423. //collision coordinator initialization. For now legacy per default.
  24424. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24425. // Uniform Buffer
  24426. _this._createUbo();
  24427. // Default Image processing definition
  24428. if (BABYLON.ImageProcessingConfiguration) {
  24429. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24430. }
  24431. return _this;
  24432. }
  24433. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24434. /**
  24435. * Texture used in all pbr material as the reflection texture.
  24436. * As in the majority of the scene they are the same (exception for multi room and so on),
  24437. * this is easier to reference from here than from all the materials.
  24438. */
  24439. get: function () {
  24440. return this._environmentTexture;
  24441. },
  24442. /**
  24443. * Texture used in all pbr material as the reflection texture.
  24444. * As in the majority of the scene they are the same (exception for multi room and so on),
  24445. * this is easier to set here than in all the materials.
  24446. */
  24447. set: function (value) {
  24448. if (this._environmentTexture === value) {
  24449. return;
  24450. }
  24451. this._environmentTexture = value;
  24452. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24453. },
  24454. enumerable: true,
  24455. configurable: true
  24456. });
  24457. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24458. /**
  24459. * Default image processing configuration used either in the rendering
  24460. * Forward main pass or through the imageProcessingPostProcess if present.
  24461. * As in the majority of the scene they are the same (exception for multi camera),
  24462. * this is easier to reference from here than from all the materials and post process.
  24463. *
  24464. * No setter as we it is a shared configuration, you can set the values instead.
  24465. */
  24466. get: function () {
  24467. return this._imageProcessingConfiguration;
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24473. get: function () {
  24474. return this._forceWireframe;
  24475. },
  24476. /**
  24477. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24478. */
  24479. set: function (value) {
  24480. if (this._forceWireframe === value) {
  24481. return;
  24482. }
  24483. this._forceWireframe = value;
  24484. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24490. get: function () {
  24491. return this._forcePointsCloud;
  24492. },
  24493. /**
  24494. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24495. */
  24496. set: function (value) {
  24497. if (this._forcePointsCloud === value) {
  24498. return;
  24499. }
  24500. this._forcePointsCloud = value;
  24501. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24507. /**
  24508. * Gets or sets the animation properties override
  24509. */
  24510. get: function () {
  24511. return this._animationPropertiesOverride;
  24512. },
  24513. set: function (value) {
  24514. this._animationPropertiesOverride = value;
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(Scene.prototype, "onDispose", {
  24520. /** Sets a function to be executed when this scene is disposed. */
  24521. set: function (callback) {
  24522. if (this._onDisposeObserver) {
  24523. this.onDisposeObservable.remove(this._onDisposeObserver);
  24524. }
  24525. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. Object.defineProperty(Scene.prototype, "beforeRender", {
  24531. /** Sets a function to be executed before rendering this scene */
  24532. set: function (callback) {
  24533. if (this._onBeforeRenderObserver) {
  24534. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24535. }
  24536. if (callback) {
  24537. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24538. }
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "afterRender", {
  24544. /** Sets a function to be executed after rendering this scene */
  24545. set: function (callback) {
  24546. if (this._onAfterRenderObserver) {
  24547. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24548. }
  24549. if (callback) {
  24550. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24551. }
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24557. /** Sets a function to be executed before rendering a camera*/
  24558. set: function (callback) {
  24559. if (this._onBeforeCameraRenderObserver) {
  24560. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24561. }
  24562. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24568. /** Sets a function to be executed after rendering a camera*/
  24569. set: function (callback) {
  24570. if (this._onAfterCameraRenderObserver) {
  24571. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24572. }
  24573. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24579. /**
  24580. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24581. */
  24582. get: function () {
  24583. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24589. get: function () {
  24590. return this._useRightHandedSystem;
  24591. },
  24592. /**
  24593. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24594. */
  24595. set: function (value) {
  24596. if (this._useRightHandedSystem === value) {
  24597. return;
  24598. }
  24599. this._useRightHandedSystem = value;
  24600. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24601. },
  24602. enumerable: true,
  24603. configurable: true
  24604. });
  24605. /**
  24606. * Sets the step Id used by deterministic lock step
  24607. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24608. * @param newStepId defines the step Id
  24609. */
  24610. Scene.prototype.setStepId = function (newStepId) {
  24611. this._currentStepId = newStepId;
  24612. };
  24613. ;
  24614. /**
  24615. * Gets the step Id used by deterministic lock step
  24616. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24617. * @returns the step Id
  24618. */
  24619. Scene.prototype.getStepId = function () {
  24620. return this._currentStepId;
  24621. };
  24622. ;
  24623. /**
  24624. * Gets the internal step used by deterministic lock step
  24625. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24626. * @returns the internal step
  24627. */
  24628. Scene.prototype.getInternalStep = function () {
  24629. return this._currentInternalStep;
  24630. };
  24631. ;
  24632. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24633. get: function () {
  24634. return this._fogEnabled;
  24635. },
  24636. /**
  24637. * Gets or sets a boolean indicating if fog is enabled on this scene
  24638. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24639. */
  24640. set: function (value) {
  24641. if (this._fogEnabled === value) {
  24642. return;
  24643. }
  24644. this._fogEnabled = value;
  24645. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(Scene.prototype, "fogMode", {
  24651. get: function () {
  24652. return this._fogMode;
  24653. },
  24654. /**
  24655. * Gets or sets the fog mode to use
  24656. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24657. */
  24658. set: function (value) {
  24659. if (this._fogMode === value) {
  24660. return;
  24661. }
  24662. this._fogMode = value;
  24663. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24664. },
  24665. enumerable: true,
  24666. configurable: true
  24667. });
  24668. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24669. get: function () {
  24670. return this._shadowsEnabled;
  24671. },
  24672. /**
  24673. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24674. */
  24675. set: function (value) {
  24676. if (this._shadowsEnabled === value) {
  24677. return;
  24678. }
  24679. this._shadowsEnabled = value;
  24680. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24681. },
  24682. enumerable: true,
  24683. configurable: true
  24684. });
  24685. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24686. get: function () {
  24687. return this._lightsEnabled;
  24688. },
  24689. /**
  24690. * Gets or sets a boolean indicating if lights are enabled on this scene
  24691. */
  24692. set: function (value) {
  24693. if (this._lightsEnabled === value) {
  24694. return;
  24695. }
  24696. this._lightsEnabled = value;
  24697. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24698. },
  24699. enumerable: true,
  24700. configurable: true
  24701. });
  24702. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24703. /** The default material used on meshes when no material is affected */
  24704. get: function () {
  24705. if (!this._defaultMaterial) {
  24706. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24707. }
  24708. return this._defaultMaterial;
  24709. },
  24710. /** The default material used on meshes when no material is affected */
  24711. set: function (value) {
  24712. this._defaultMaterial = value;
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24718. get: function () {
  24719. return this._texturesEnabled;
  24720. },
  24721. /**
  24722. * Gets or sets a boolean indicating if textures are enabled on this scene
  24723. */
  24724. set: function (value) {
  24725. if (this._texturesEnabled === value) {
  24726. return;
  24727. }
  24728. this._texturesEnabled = value;
  24729. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24730. },
  24731. enumerable: true,
  24732. configurable: true
  24733. });
  24734. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24735. get: function () {
  24736. return this._skeletonsEnabled;
  24737. },
  24738. /**
  24739. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24740. */
  24741. set: function (value) {
  24742. if (this._skeletonsEnabled === value) {
  24743. return;
  24744. }
  24745. this._skeletonsEnabled = value;
  24746. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24752. /**
  24753. * Gets the main soundtrack associated with the scene
  24754. */
  24755. get: function () {
  24756. if (!this._mainSoundTrack) {
  24757. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24758. }
  24759. return this._mainSoundTrack;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24765. /** @hidden */
  24766. get: function () {
  24767. return this._alternateRendering;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24773. /**
  24774. * Gets the list of frustum planes (built from the active camera)
  24775. */
  24776. get: function () {
  24777. return this._frustumPlanes;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. /**
  24783. * Registers the transient components if needed.
  24784. */
  24785. Scene.prototype._registerTransientComponents = function () {
  24786. // Register components that have been associated lately to the scene.
  24787. if (this._transientComponents.length > 0) {
  24788. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24789. var component = _a[_i];
  24790. component.register();
  24791. }
  24792. this._transientComponents = [];
  24793. }
  24794. };
  24795. /**
  24796. * @hidden
  24797. * Add a component to the scene.
  24798. * Note that the ccomponent could be registered on th next frame if this is called after
  24799. * the register component stage.
  24800. * @param component Defines the component to add to the scene
  24801. */
  24802. Scene.prototype._addComponent = function (component) {
  24803. this._components.push(component);
  24804. this._transientComponents.push(component);
  24805. var serializableComponent = component;
  24806. if (serializableComponent.addFromContainer) {
  24807. this._serializableComponents.push(serializableComponent);
  24808. }
  24809. };
  24810. /**
  24811. * @hidden
  24812. * Gets a component from the scene.
  24813. * @param name defines the name of the component to retrieve
  24814. * @returns the component or null if not present
  24815. */
  24816. Scene.prototype._getComponent = function (name) {
  24817. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24818. var component = _a[_i];
  24819. if (component.name === name) {
  24820. return component;
  24821. }
  24822. }
  24823. return null;
  24824. };
  24825. Object.defineProperty(Scene.prototype, "debugLayer", {
  24826. /**
  24827. * Gets the debug layer (aka Inspector) associated with the scene
  24828. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24829. */
  24830. get: function () {
  24831. if (!this._debugLayer) {
  24832. this._debugLayer = new BABYLON.DebugLayer(this);
  24833. }
  24834. return this._debugLayer;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24840. /**
  24841. * Gets a boolean indicating if collisions are processed on a web worker
  24842. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24843. */
  24844. get: function () {
  24845. return this._workerCollisions;
  24846. },
  24847. set: function (enabled) {
  24848. if (!BABYLON.CollisionCoordinatorLegacy) {
  24849. return;
  24850. }
  24851. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24852. this._workerCollisions = enabled;
  24853. if (this.collisionCoordinator) {
  24854. this.collisionCoordinator.destroy();
  24855. }
  24856. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24857. this.collisionCoordinator.init(this);
  24858. },
  24859. enumerable: true,
  24860. configurable: true
  24861. });
  24862. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24863. /**
  24864. * Gets the octree used to boost mesh selection (picking)
  24865. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24866. */
  24867. get: function () {
  24868. return this._selectionOctree;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24874. /**
  24875. * Gets the mesh that is currently under the pointer
  24876. */
  24877. get: function () {
  24878. return this._pointerOverMesh;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(Scene.prototype, "pointerX", {
  24884. /**
  24885. * Gets the current on-screen X position of the pointer
  24886. */
  24887. get: function () {
  24888. return this._pointerX;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. Object.defineProperty(Scene.prototype, "pointerY", {
  24894. /**
  24895. * Gets the current on-screen Y position of the pointer
  24896. */
  24897. get: function () {
  24898. return this._pointerY;
  24899. },
  24900. enumerable: true,
  24901. configurable: true
  24902. });
  24903. /**
  24904. * Gets the cached material (ie. the latest rendered one)
  24905. * @returns the cached material
  24906. */
  24907. Scene.prototype.getCachedMaterial = function () {
  24908. return this._cachedMaterial;
  24909. };
  24910. /**
  24911. * Gets the cached effect (ie. the latest rendered one)
  24912. * @returns the cached effect
  24913. */
  24914. Scene.prototype.getCachedEffect = function () {
  24915. return this._cachedEffect;
  24916. };
  24917. /**
  24918. * Gets the cached visibility state (ie. the latest rendered one)
  24919. * @returns the cached visibility state
  24920. */
  24921. Scene.prototype.getCachedVisibility = function () {
  24922. return this._cachedVisibility;
  24923. };
  24924. /**
  24925. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24926. * @param material defines the current material
  24927. * @param effect defines the current effect
  24928. * @param visibility defines the current visibility state
  24929. * @returns true if one parameter is not cached
  24930. */
  24931. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24932. if (visibility === void 0) { visibility = 1; }
  24933. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24934. };
  24935. /**
  24936. * Gets the engine associated with the scene
  24937. * @returns an Engine
  24938. */
  24939. Scene.prototype.getEngine = function () {
  24940. return this._engine;
  24941. };
  24942. /**
  24943. * Gets the total number of vertices rendered per frame
  24944. * @returns the total number of vertices rendered per frame
  24945. */
  24946. Scene.prototype.getTotalVertices = function () {
  24947. return this._totalVertices.current;
  24948. };
  24949. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24950. /**
  24951. * Gets the performance counter for total vertices
  24952. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24953. */
  24954. get: function () {
  24955. return this._totalVertices;
  24956. },
  24957. enumerable: true,
  24958. configurable: true
  24959. });
  24960. /**
  24961. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24962. * @returns the total number of active indices rendered per frame
  24963. */
  24964. Scene.prototype.getActiveIndices = function () {
  24965. return this._activeIndices.current;
  24966. };
  24967. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24968. /**
  24969. * Gets the performance counter for active indices
  24970. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24971. */
  24972. get: function () {
  24973. return this._activeIndices;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. /**
  24979. * Gets the total number of active particles rendered per frame
  24980. * @returns the total number of active particles rendered per frame
  24981. */
  24982. Scene.prototype.getActiveParticles = function () {
  24983. return this._activeParticles.current;
  24984. };
  24985. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24986. /**
  24987. * Gets the performance counter for active particles
  24988. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24989. */
  24990. get: function () {
  24991. return this._activeParticles;
  24992. },
  24993. enumerable: true,
  24994. configurable: true
  24995. });
  24996. /**
  24997. * Gets the total number of active bones rendered per frame
  24998. * @returns the total number of active bones rendered per frame
  24999. */
  25000. Scene.prototype.getActiveBones = function () {
  25001. return this._activeBones.current;
  25002. };
  25003. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25004. /**
  25005. * Gets the performance counter for active bones
  25006. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25007. */
  25008. get: function () {
  25009. return this._activeBones;
  25010. },
  25011. enumerable: true,
  25012. configurable: true
  25013. });
  25014. /** @hidden */
  25015. Scene.prototype.getInterFramePerfCounter = function () {
  25016. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25017. return 0;
  25018. };
  25019. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25020. /** @hidden */
  25021. get: function () {
  25022. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25023. return null;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. /** @hidden */
  25029. Scene.prototype.getLastFrameDuration = function () {
  25030. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25031. return 0;
  25032. };
  25033. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25034. /** @hidden */
  25035. get: function () {
  25036. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25037. return null;
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. /** @hidden */
  25043. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25044. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25045. return 0;
  25046. };
  25047. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25048. /** @hidden */
  25049. get: function () {
  25050. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25051. return null;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. /**
  25057. * Gets the array of active meshes
  25058. * @returns an array of AbstractMesh
  25059. */
  25060. Scene.prototype.getActiveMeshes = function () {
  25061. return this._activeMeshes;
  25062. };
  25063. /** @hidden */
  25064. Scene.prototype.getRenderTargetsDuration = function () {
  25065. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25066. return 0;
  25067. };
  25068. /** @hidden */
  25069. Scene.prototype.getRenderDuration = function () {
  25070. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25071. return 0;
  25072. };
  25073. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25074. /** @hidden */
  25075. get: function () {
  25076. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25077. return null;
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. /** @hidden */
  25083. Scene.prototype.getParticlesDuration = function () {
  25084. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25085. return 0;
  25086. };
  25087. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25088. /** @hidden */
  25089. get: function () {
  25090. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25091. return null;
  25092. },
  25093. enumerable: true,
  25094. configurable: true
  25095. });
  25096. /** @hidden */
  25097. Scene.prototype.getSpritesDuration = function () {
  25098. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25099. return 0;
  25100. };
  25101. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25102. /** @hidden */
  25103. get: function () {
  25104. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25105. return null;
  25106. },
  25107. enumerable: true,
  25108. configurable: true
  25109. });
  25110. /**
  25111. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25112. * @returns a number
  25113. */
  25114. Scene.prototype.getAnimationRatio = function () {
  25115. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25116. };
  25117. /**
  25118. * Gets an unique Id for the current frame
  25119. * @returns a number
  25120. */
  25121. Scene.prototype.getRenderId = function () {
  25122. return this._renderId;
  25123. };
  25124. /** Call this function if you want to manually increment the render Id*/
  25125. Scene.prototype.incrementRenderId = function () {
  25126. this._renderId++;
  25127. };
  25128. Scene.prototype._updatePointerPosition = function (evt) {
  25129. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25130. if (!canvasRect) {
  25131. return;
  25132. }
  25133. this._pointerX = evt.clientX - canvasRect.left;
  25134. this._pointerY = evt.clientY - canvasRect.top;
  25135. this._unTranslatedPointerX = this._pointerX;
  25136. this._unTranslatedPointerY = this._pointerY;
  25137. };
  25138. Scene.prototype._createUbo = function () {
  25139. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25140. this._sceneUbo.addUniform("viewProjection", 16);
  25141. this._sceneUbo.addUniform("view", 16);
  25142. };
  25143. Scene.prototype._createAlternateUbo = function () {
  25144. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25145. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25146. this._alternateSceneUbo.addUniform("view", 16);
  25147. };
  25148. // Pointers handling
  25149. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25150. if (pointerInfo.pickInfo) {
  25151. if (!pointerInfo.pickInfo.ray) {
  25152. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25153. }
  25154. }
  25155. };
  25156. /**
  25157. * Use this method to simulate a pointer move on a mesh
  25158. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25159. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25160. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25161. * @returns the current scene
  25162. */
  25163. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25164. var evt = new PointerEvent("pointermove", pointerEventInit);
  25165. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25166. return this;
  25167. }
  25168. return this._processPointerMove(pickResult, evt);
  25169. };
  25170. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25171. var canvas = this._engine.getRenderingCanvas();
  25172. if (!canvas) {
  25173. return this;
  25174. }
  25175. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25176. if (isMeshPicked) {
  25177. this.setPointerOverMesh(pickResult.pickedMesh);
  25178. }
  25179. else {
  25180. this.setPointerOverMesh(null);
  25181. }
  25182. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25183. var step = _a[_i];
  25184. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25185. }
  25186. if (pickResult) {
  25187. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25188. if (this.onPointerMove) {
  25189. this.onPointerMove(evt, pickResult, type);
  25190. }
  25191. if (this.onPointerObservable.hasObservers()) {
  25192. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25193. this._setRayOnPointerInfo(pi);
  25194. this.onPointerObservable.notifyObservers(pi, type);
  25195. }
  25196. }
  25197. return this;
  25198. };
  25199. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25200. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25201. if (pickResult) {
  25202. pi.ray = pickResult.ray;
  25203. }
  25204. this.onPrePointerObservable.notifyObservers(pi, type);
  25205. if (pi.skipOnPointerObservable) {
  25206. return true;
  25207. }
  25208. else {
  25209. return false;
  25210. }
  25211. };
  25212. /**
  25213. * Use this method to simulate a pointer down on a mesh
  25214. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25215. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25216. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25217. * @returns the current scene
  25218. */
  25219. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25220. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25221. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25222. return this;
  25223. }
  25224. return this._processPointerDown(pickResult, evt);
  25225. };
  25226. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25227. var _this = this;
  25228. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25229. this._pickedDownMesh = pickResult.pickedMesh;
  25230. var actionManager = pickResult.pickedMesh.actionManager;
  25231. if (actionManager) {
  25232. if (actionManager.hasPickTriggers) {
  25233. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25234. switch (evt.button) {
  25235. case 0:
  25236. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. break;
  25238. case 1:
  25239. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25240. break;
  25241. case 2:
  25242. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25243. break;
  25244. }
  25245. }
  25246. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25247. window.setTimeout(function () {
  25248. 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);
  25249. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25250. if (_this._totalPointersPressed !== 0 &&
  25251. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25252. !_this._isPointerSwiping()) {
  25253. _this._startingPointerTime = 0;
  25254. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25255. }
  25256. }
  25257. }, Scene.LongPressDelay);
  25258. }
  25259. }
  25260. }
  25261. else {
  25262. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25263. var step = _a[_i];
  25264. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25265. }
  25266. }
  25267. if (pickResult) {
  25268. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25269. if (this.onPointerDown) {
  25270. this.onPointerDown(evt, pickResult, type);
  25271. }
  25272. if (this.onPointerObservable.hasObservers()) {
  25273. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25274. this._setRayOnPointerInfo(pi);
  25275. this.onPointerObservable.notifyObservers(pi, type);
  25276. }
  25277. }
  25278. return this;
  25279. };
  25280. /**
  25281. * Use this method to simulate a pointer up on a mesh
  25282. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25283. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25284. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25285. * @returns the current scene
  25286. */
  25287. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25288. var evt = new PointerEvent("pointerup", pointerEventInit);
  25289. var clickInfo = new ClickInfo();
  25290. clickInfo.singleClick = true;
  25291. clickInfo.ignore = true;
  25292. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25293. return this;
  25294. }
  25295. return this._processPointerUp(pickResult, evt, clickInfo);
  25296. };
  25297. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25298. if (pickResult && pickResult && pickResult.pickedMesh) {
  25299. this._pickedUpMesh = pickResult.pickedMesh;
  25300. if (this._pickedDownMesh === this._pickedUpMesh) {
  25301. if (this.onPointerPick) {
  25302. this.onPointerPick(evt, pickResult);
  25303. }
  25304. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25305. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25306. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25307. this._setRayOnPointerInfo(pi);
  25308. this.onPointerObservable.notifyObservers(pi, type_1);
  25309. }
  25310. }
  25311. if (pickResult.pickedMesh.actionManager) {
  25312. if (clickInfo.ignore) {
  25313. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25314. }
  25315. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25316. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25317. }
  25318. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25319. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25320. }
  25321. }
  25322. }
  25323. else {
  25324. if (!clickInfo.ignore) {
  25325. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25326. var step = _a[_i];
  25327. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25328. }
  25329. }
  25330. }
  25331. if (this._pickedDownMesh &&
  25332. this._pickedDownMesh.actionManager &&
  25333. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25334. this._pickedDownMesh !== this._pickedUpMesh) {
  25335. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25336. }
  25337. var type = BABYLON.PointerEventTypes.POINTERUP;
  25338. if (this.onPointerObservable.hasObservers()) {
  25339. if (!clickInfo.ignore) {
  25340. if (!clickInfo.hasSwiped) {
  25341. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25342. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25343. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25344. this._setRayOnPointerInfo(pi);
  25345. this.onPointerObservable.notifyObservers(pi, type_2);
  25346. }
  25347. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25348. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25349. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25350. this._setRayOnPointerInfo(pi);
  25351. this.onPointerObservable.notifyObservers(pi, type_3);
  25352. }
  25353. }
  25354. }
  25355. else {
  25356. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25357. this._setRayOnPointerInfo(pi);
  25358. this.onPointerObservable.notifyObservers(pi, type);
  25359. }
  25360. }
  25361. if (this.onPointerUp) {
  25362. this.onPointerUp(evt, pickResult, type);
  25363. }
  25364. return this;
  25365. };
  25366. /**
  25367. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25368. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25369. * @returns true if the pointer was captured
  25370. */
  25371. Scene.prototype.isPointerCaptured = function (pointerId) {
  25372. if (pointerId === void 0) { pointerId = 0; }
  25373. return this._pointerCaptures[pointerId];
  25374. };
  25375. /** @hidden */
  25376. Scene.prototype._isPointerSwiping = function () {
  25377. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25378. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25379. };
  25380. /**
  25381. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25382. * @param attachUp defines if you want to attach events to pointerup
  25383. * @param attachDown defines if you want to attach events to pointerdown
  25384. * @param attachMove defines if you want to attach events to pointermove
  25385. */
  25386. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25387. var _this = this;
  25388. if (attachUp === void 0) { attachUp = true; }
  25389. if (attachDown === void 0) { attachDown = true; }
  25390. if (attachMove === void 0) { attachMove = true; }
  25391. this._initActionManager = function (act, clickInfo) {
  25392. if (!_this._meshPickProceed) {
  25393. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25394. _this._currentPickResult = pickResult;
  25395. if (pickResult) {
  25396. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25397. }
  25398. _this._meshPickProceed = true;
  25399. }
  25400. return act;
  25401. };
  25402. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25403. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25404. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25405. btn !== _this._previousButtonPressed) {
  25406. _this._doubleClickOccured = false;
  25407. clickInfo.singleClick = true;
  25408. clickInfo.ignore = false;
  25409. cb(clickInfo, _this._currentPickResult);
  25410. }
  25411. };
  25412. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25413. var clickInfo = new ClickInfo();
  25414. _this._currentPickResult = null;
  25415. var act = null;
  25416. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25417. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25418. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25419. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25420. act = _this._initActionManager(act, clickInfo);
  25421. if (act)
  25422. checkPicking = act.hasPickTriggers;
  25423. }
  25424. if (checkPicking) {
  25425. var btn = evt.button;
  25426. clickInfo.hasSwiped = _this._isPointerSwiping();
  25427. if (!clickInfo.hasSwiped) {
  25428. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25429. if (!checkSingleClickImmediately) {
  25430. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25431. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25432. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25433. act = _this._initActionManager(act, clickInfo);
  25434. if (act)
  25435. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25436. }
  25437. }
  25438. if (checkSingleClickImmediately) {
  25439. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25440. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25441. btn !== _this._previousButtonPressed) {
  25442. clickInfo.singleClick = true;
  25443. cb(clickInfo, _this._currentPickResult);
  25444. }
  25445. }
  25446. // at least one double click is required to be check and exclusive double click is enabled
  25447. else {
  25448. // wait that no double click has been raised during the double click delay
  25449. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25450. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25451. }
  25452. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25453. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25454. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25455. act = _this._initActionManager(act, clickInfo);
  25456. if (act)
  25457. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25458. }
  25459. if (checkDoubleClick) {
  25460. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25461. if (btn === _this._previousButtonPressed &&
  25462. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25463. !_this._doubleClickOccured) {
  25464. // pointer has not moved for 2 clicks, it's a double click
  25465. if (!clickInfo.hasSwiped &&
  25466. !_this._isPointerSwiping()) {
  25467. _this._previousStartingPointerTime = 0;
  25468. _this._doubleClickOccured = true;
  25469. clickInfo.doubleClick = true;
  25470. clickInfo.ignore = false;
  25471. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25472. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25473. }
  25474. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25475. cb(clickInfo, _this._currentPickResult);
  25476. }
  25477. // if the two successive clicks are too far, it's just two simple clicks
  25478. else {
  25479. _this._doubleClickOccured = false;
  25480. _this._previousStartingPointerTime = _this._startingPointerTime;
  25481. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25482. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25483. _this._previousButtonPressed = btn;
  25484. if (Scene.ExclusiveDoubleClickMode) {
  25485. if (_this._previousDelayedSimpleClickTimeout) {
  25486. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25487. }
  25488. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25489. cb(clickInfo, _this._previousPickResult);
  25490. }
  25491. else {
  25492. cb(clickInfo, _this._currentPickResult);
  25493. }
  25494. }
  25495. }
  25496. // just the first click of the double has been raised
  25497. else {
  25498. _this._doubleClickOccured = false;
  25499. _this._previousStartingPointerTime = _this._startingPointerTime;
  25500. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25501. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25502. _this._previousButtonPressed = btn;
  25503. }
  25504. }
  25505. }
  25506. }
  25507. clickInfo.ignore = true;
  25508. cb(clickInfo, _this._currentPickResult);
  25509. };
  25510. this._onPointerMove = function (evt) {
  25511. _this._updatePointerPosition(evt);
  25512. // PreObservable support
  25513. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25514. return;
  25515. }
  25516. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25517. return;
  25518. }
  25519. if (!_this.pointerMovePredicate) {
  25520. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25521. }
  25522. // Meshes
  25523. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25524. _this._processPointerMove(pickResult, evt);
  25525. };
  25526. this._onPointerDown = function (evt) {
  25527. _this._totalPointersPressed++;
  25528. _this._pickedDownMesh = null;
  25529. _this._meshPickProceed = false;
  25530. _this._updatePointerPosition(evt);
  25531. if (_this.preventDefaultOnPointerDown && canvas) {
  25532. evt.preventDefault();
  25533. canvas.focus();
  25534. }
  25535. // PreObservable support
  25536. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25537. return;
  25538. }
  25539. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25540. return;
  25541. }
  25542. _this._pointerCaptures[evt.pointerId] = true;
  25543. _this._startingPointerPosition.x = _this._pointerX;
  25544. _this._startingPointerPosition.y = _this._pointerY;
  25545. _this._startingPointerTime = Date.now();
  25546. if (!_this.pointerDownPredicate) {
  25547. _this.pointerDownPredicate = function (mesh) {
  25548. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25549. };
  25550. }
  25551. // Meshes
  25552. _this._pickedDownMesh = null;
  25553. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25554. _this._processPointerDown(pickResult, evt);
  25555. };
  25556. this._onPointerUp = function (evt) {
  25557. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25558. return; // So we need to test it the pointer down was pressed before.
  25559. }
  25560. _this._totalPointersPressed--;
  25561. _this._pickedUpMesh = null;
  25562. _this._meshPickProceed = false;
  25563. _this._updatePointerPosition(evt);
  25564. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25565. // PreObservable support
  25566. if (_this.onPrePointerObservable.hasObservers()) {
  25567. if (!clickInfo.ignore) {
  25568. if (!clickInfo.hasSwiped) {
  25569. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25570. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25571. return;
  25572. }
  25573. }
  25574. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25575. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25576. return;
  25577. }
  25578. }
  25579. }
  25580. }
  25581. else {
  25582. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25583. return;
  25584. }
  25585. }
  25586. }
  25587. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25588. return;
  25589. }
  25590. _this._pointerCaptures[evt.pointerId] = false;
  25591. if (!_this.pointerUpPredicate) {
  25592. _this.pointerUpPredicate = function (mesh) {
  25593. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25594. };
  25595. }
  25596. // Meshes
  25597. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25598. _this._initActionManager(null, clickInfo);
  25599. }
  25600. if (!pickResult) {
  25601. pickResult = _this._currentPickResult;
  25602. }
  25603. _this._processPointerUp(pickResult, evt, clickInfo);
  25604. _this._previousPickResult = _this._currentPickResult;
  25605. });
  25606. };
  25607. this._onKeyDown = function (evt) {
  25608. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25609. if (_this.onPreKeyboardObservable.hasObservers()) {
  25610. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25611. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25612. if (pi.skipOnPointerObservable) {
  25613. return;
  25614. }
  25615. }
  25616. if (_this.onKeyboardObservable.hasObservers()) {
  25617. var pi = new BABYLON.KeyboardInfo(type, evt);
  25618. _this.onKeyboardObservable.notifyObservers(pi, type);
  25619. }
  25620. if (_this.actionManager) {
  25621. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25622. }
  25623. };
  25624. this._onKeyUp = function (evt) {
  25625. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25626. if (_this.onPreKeyboardObservable.hasObservers()) {
  25627. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25628. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25629. if (pi.skipOnPointerObservable) {
  25630. return;
  25631. }
  25632. }
  25633. if (_this.onKeyboardObservable.hasObservers()) {
  25634. var pi = new BABYLON.KeyboardInfo(type, evt);
  25635. _this.onKeyboardObservable.notifyObservers(pi, type);
  25636. }
  25637. if (_this.actionManager) {
  25638. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25639. }
  25640. };
  25641. var engine = this.getEngine();
  25642. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25643. if (!canvas) {
  25644. return;
  25645. }
  25646. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25647. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25648. });
  25649. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25650. if (!canvas) {
  25651. return;
  25652. }
  25653. canvas.removeEventListener("keydown", _this._onKeyDown);
  25654. canvas.removeEventListener("keyup", _this._onKeyUp);
  25655. });
  25656. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25657. var canvas = this._engine.getRenderingCanvas();
  25658. if (!canvas) {
  25659. return;
  25660. }
  25661. if (attachMove) {
  25662. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25663. // Wheel
  25664. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25665. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25666. }
  25667. if (attachDown) {
  25668. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25669. }
  25670. if (attachUp) {
  25671. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25672. }
  25673. canvas.tabIndex = 1;
  25674. };
  25675. /** Detaches all event handlers*/
  25676. Scene.prototype.detachControl = function () {
  25677. var engine = this.getEngine();
  25678. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25679. var canvas = engine.getRenderingCanvas();
  25680. if (!canvas) {
  25681. return;
  25682. }
  25683. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25684. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25685. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25686. if (this._onCanvasBlurObserver) {
  25687. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25688. }
  25689. if (this._onCanvasFocusObserver) {
  25690. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25691. }
  25692. // Wheel
  25693. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25694. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25695. // Keyboard
  25696. canvas.removeEventListener("keydown", this._onKeyDown);
  25697. canvas.removeEventListener("keyup", this._onKeyUp);
  25698. // Observables
  25699. this.onKeyboardObservable.clear();
  25700. this.onPreKeyboardObservable.clear();
  25701. this.onPointerObservable.clear();
  25702. this.onPrePointerObservable.clear();
  25703. };
  25704. /**
  25705. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25706. * Delay loaded resources are not taking in account
  25707. * @return true if all required resources are ready
  25708. */
  25709. Scene.prototype.isReady = function () {
  25710. if (this._isDisposed) {
  25711. return false;
  25712. }
  25713. if (this._pendingData.length > 0) {
  25714. return false;
  25715. }
  25716. var index;
  25717. var engine = this.getEngine();
  25718. // Geometries
  25719. for (index = 0; index < this.geometries.length; index++) {
  25720. var geometry = this.geometries[index];
  25721. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25722. return false;
  25723. }
  25724. }
  25725. // Meshes
  25726. for (index = 0; index < this.meshes.length; index++) {
  25727. var mesh = this.meshes[index];
  25728. if (!mesh.isEnabled()) {
  25729. continue;
  25730. }
  25731. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25732. continue;
  25733. }
  25734. if (!mesh.isReady(true)) {
  25735. return false;
  25736. }
  25737. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25738. // Is Ready For Mesh
  25739. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25740. var step = _a[_i];
  25741. if (!step.action(mesh, hardwareInstancedRendering)) {
  25742. return false;
  25743. }
  25744. }
  25745. }
  25746. // Post-processes
  25747. if (this.activeCameras && this.activeCameras.length > 0) {
  25748. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25749. var camera = _c[_b];
  25750. if (!camera.isReady(true)) {
  25751. return false;
  25752. }
  25753. }
  25754. }
  25755. else if (this.activeCamera) {
  25756. if (!this.activeCamera.isReady(true)) {
  25757. return false;
  25758. }
  25759. }
  25760. // Particles
  25761. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25762. var particleSystem = _e[_d];
  25763. if (!particleSystem.isReady()) {
  25764. return false;
  25765. }
  25766. }
  25767. return true;
  25768. };
  25769. /** Resets all cached information relative to material (including effect and visibility) */
  25770. Scene.prototype.resetCachedMaterial = function () {
  25771. this._cachedMaterial = null;
  25772. this._cachedEffect = null;
  25773. this._cachedVisibility = null;
  25774. };
  25775. /**
  25776. * Registers a function to be called before every frame render
  25777. * @param func defines the function to register
  25778. */
  25779. Scene.prototype.registerBeforeRender = function (func) {
  25780. this.onBeforeRenderObservable.add(func);
  25781. };
  25782. /**
  25783. * Unregisters a function called before every frame render
  25784. * @param func defines the function to unregister
  25785. */
  25786. Scene.prototype.unregisterBeforeRender = function (func) {
  25787. this.onBeforeRenderObservable.removeCallback(func);
  25788. };
  25789. /**
  25790. * Registers a function to be called after every frame render
  25791. * @param func defines the function to register
  25792. */
  25793. Scene.prototype.registerAfterRender = function (func) {
  25794. this.onAfterRenderObservable.add(func);
  25795. };
  25796. /**
  25797. * Unregisters a function called after every frame render
  25798. * @param func defines the function to unregister
  25799. */
  25800. Scene.prototype.unregisterAfterRender = function (func) {
  25801. this.onAfterRenderObservable.removeCallback(func);
  25802. };
  25803. Scene.prototype._executeOnceBeforeRender = function (func) {
  25804. var _this = this;
  25805. var execFunc = function () {
  25806. func();
  25807. setTimeout(function () {
  25808. _this.unregisterBeforeRender(execFunc);
  25809. });
  25810. };
  25811. this.registerBeforeRender(execFunc);
  25812. };
  25813. /**
  25814. * The provided function will run before render once and will be disposed afterwards.
  25815. * A timeout delay can be provided so that the function will be executed in N ms.
  25816. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25817. * @param func The function to be executed.
  25818. * @param timeout optional delay in ms
  25819. */
  25820. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25821. var _this = this;
  25822. if (timeout !== undefined) {
  25823. setTimeout(function () {
  25824. _this._executeOnceBeforeRender(func);
  25825. }, timeout);
  25826. }
  25827. else {
  25828. this._executeOnceBeforeRender(func);
  25829. }
  25830. };
  25831. /** @hidden */
  25832. Scene.prototype._addPendingData = function (data) {
  25833. this._pendingData.push(data);
  25834. };
  25835. /** @hidden */
  25836. Scene.prototype._removePendingData = function (data) {
  25837. var wasLoading = this.isLoading;
  25838. var index = this._pendingData.indexOf(data);
  25839. if (index !== -1) {
  25840. this._pendingData.splice(index, 1);
  25841. }
  25842. if (wasLoading && !this.isLoading) {
  25843. this.onDataLoadedObservable.notifyObservers(this);
  25844. }
  25845. };
  25846. /**
  25847. * Returns the number of items waiting to be loaded
  25848. * @returns the number of items waiting to be loaded
  25849. */
  25850. Scene.prototype.getWaitingItemsCount = function () {
  25851. return this._pendingData.length;
  25852. };
  25853. Object.defineProperty(Scene.prototype, "isLoading", {
  25854. /**
  25855. * Returns a boolean indicating if the scene is still loading data
  25856. */
  25857. get: function () {
  25858. return this._pendingData.length > 0;
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. /**
  25864. * Registers a function to be executed when the scene is ready
  25865. * @param {Function} func - the function to be executed
  25866. */
  25867. Scene.prototype.executeWhenReady = function (func) {
  25868. var _this = this;
  25869. this.onReadyObservable.add(func);
  25870. if (this._executeWhenReadyTimeoutId !== -1) {
  25871. return;
  25872. }
  25873. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25874. _this._checkIsReady();
  25875. }, 150);
  25876. };
  25877. /**
  25878. * Returns a promise that resolves when the scene is ready
  25879. * @returns A promise that resolves when the scene is ready
  25880. */
  25881. Scene.prototype.whenReadyAsync = function () {
  25882. var _this = this;
  25883. return new Promise(function (resolve) {
  25884. _this.executeWhenReady(function () {
  25885. resolve();
  25886. });
  25887. });
  25888. };
  25889. /** @hidden */
  25890. Scene.prototype._checkIsReady = function () {
  25891. var _this = this;
  25892. this._registerTransientComponents();
  25893. if (this.isReady()) {
  25894. this.onReadyObservable.notifyObservers(this);
  25895. this.onReadyObservable.clear();
  25896. this._executeWhenReadyTimeoutId = -1;
  25897. return;
  25898. }
  25899. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25900. _this._checkIsReady();
  25901. }, 150);
  25902. };
  25903. // Animations
  25904. /**
  25905. * Will start the animation sequence of a given target
  25906. * @param target defines the target
  25907. * @param from defines from which frame should animation start
  25908. * @param to defines until which frame should animation run.
  25909. * @param weight defines the weight to apply to the animation (1.0 by default)
  25910. * @param loop defines if the animation loops
  25911. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25912. * @param onAnimationEnd defines the function to be executed when the animation ends
  25913. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25914. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25915. * @returns the animatable object created for this animation
  25916. */
  25917. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25918. if (weight === void 0) { weight = 1.0; }
  25919. if (speedRatio === void 0) { speedRatio = 1.0; }
  25920. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25921. returnedAnimatable.weight = weight;
  25922. return returnedAnimatable;
  25923. };
  25924. /**
  25925. * Will start the animation sequence of a given target
  25926. * @param target defines the target
  25927. * @param from defines from which frame should animation start
  25928. * @param to defines until which frame should animation run.
  25929. * @param loop defines if the animation loops
  25930. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25931. * @param onAnimationEnd defines the function to be executed when the animation ends
  25932. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25933. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25934. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25935. * @returns the animatable object created for this animation
  25936. */
  25937. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25938. if (speedRatio === void 0) { speedRatio = 1.0; }
  25939. if (stopCurrent === void 0) { stopCurrent = true; }
  25940. if (from > to && speedRatio > 0) {
  25941. speedRatio *= -1;
  25942. }
  25943. if (stopCurrent) {
  25944. this.stopAnimation(target, undefined, targetMask);
  25945. }
  25946. if (!animatable) {
  25947. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25948. }
  25949. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25950. // Local animations
  25951. if (target.animations && shouldRunTargetAnimations) {
  25952. animatable.appendAnimations(target, target.animations);
  25953. }
  25954. // Children animations
  25955. if (target.getAnimatables) {
  25956. var animatables = target.getAnimatables();
  25957. for (var index = 0; index < animatables.length; index++) {
  25958. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25959. }
  25960. }
  25961. animatable.reset();
  25962. return animatable;
  25963. };
  25964. /**
  25965. * Begin a new animation on a given node
  25966. * @param target defines the target where the animation will take place
  25967. * @param animations defines the list of animations to start
  25968. * @param from defines the initial value
  25969. * @param to defines the final value
  25970. * @param loop defines if you want animation to loop (off by default)
  25971. * @param speedRatio defines the speed ratio to apply to all animations
  25972. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25973. * @returns the list of created animatables
  25974. */
  25975. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25976. if (speedRatio === undefined) {
  25977. speedRatio = 1.0;
  25978. }
  25979. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25980. return animatable;
  25981. };
  25982. /**
  25983. * Begin a new animation on a given node and its hierarchy
  25984. * @param target defines the root node where the animation will take place
  25985. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25986. * @param animations defines the list of animations to start
  25987. * @param from defines the initial value
  25988. * @param to defines the final value
  25989. * @param loop defines if you want animation to loop (off by default)
  25990. * @param speedRatio defines the speed ratio to apply to all animations
  25991. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25992. * @returns the list of animatables created for all nodes
  25993. */
  25994. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25995. var children = target.getDescendants(directDescendantsOnly);
  25996. var result = [];
  25997. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25998. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25999. var child = children_1[_i];
  26000. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26001. }
  26002. return result;
  26003. };
  26004. /**
  26005. * Gets the animatable associated with a specific target
  26006. * @param target defines the target of the animatable
  26007. * @returns the required animatable if found
  26008. */
  26009. Scene.prototype.getAnimatableByTarget = function (target) {
  26010. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26011. if (this._activeAnimatables[index].target === target) {
  26012. return this._activeAnimatables[index];
  26013. }
  26014. }
  26015. return null;
  26016. };
  26017. /**
  26018. * Gets all animatables associated with a given target
  26019. * @param target defines the target to look animatables for
  26020. * @returns an array of Animatables
  26021. */
  26022. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26023. var result = [];
  26024. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26025. if (this._activeAnimatables[index].target === target) {
  26026. result.push(this._activeAnimatables[index]);
  26027. }
  26028. }
  26029. return result;
  26030. };
  26031. Object.defineProperty(Scene.prototype, "animatables", {
  26032. /**
  26033. * Gets all animatable attached to the scene
  26034. */
  26035. get: function () {
  26036. return this._activeAnimatables;
  26037. },
  26038. enumerable: true,
  26039. configurable: true
  26040. });
  26041. /**
  26042. * Will stop the animation of the given target
  26043. * @param target - the target
  26044. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26045. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26046. */
  26047. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26048. var animatables = this.getAllAnimatablesByTarget(target);
  26049. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26050. var animatable = animatables_1[_i];
  26051. animatable.stop(animationName, targetMask);
  26052. }
  26053. };
  26054. /**
  26055. * Stops and removes all animations that have been applied to the scene
  26056. */
  26057. Scene.prototype.stopAllAnimations = function () {
  26058. if (this._activeAnimatables) {
  26059. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26060. this._activeAnimatables[i].stop();
  26061. }
  26062. this._activeAnimatables = [];
  26063. }
  26064. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26065. var group = _a[_i];
  26066. group.stop();
  26067. }
  26068. };
  26069. Scene.prototype._animate = function () {
  26070. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26071. return;
  26072. }
  26073. // Getting time
  26074. var now = BABYLON.Tools.Now;
  26075. if (!this._animationTimeLast) {
  26076. if (this._pendingData.length > 0) {
  26077. return;
  26078. }
  26079. this._animationTimeLast = now;
  26080. }
  26081. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26082. this._animationTime += deltaTime;
  26083. this._animationTimeLast = now;
  26084. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26085. this._activeAnimatables[index]._animate(this._animationTime);
  26086. }
  26087. // Late animation bindings
  26088. this._processLateAnimationBindings();
  26089. };
  26090. /** @hidden */
  26091. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26092. var target = runtimeAnimation.target;
  26093. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26094. if (!target._lateAnimationHolders) {
  26095. target._lateAnimationHolders = {};
  26096. }
  26097. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26098. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26099. totalWeight: 0,
  26100. animations: [],
  26101. originalValue: originalValue
  26102. };
  26103. }
  26104. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26105. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26106. };
  26107. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26108. var normalizer = 1.0;
  26109. var finalPosition = BABYLON.Tmp.Vector3[0];
  26110. var finalScaling = BABYLON.Tmp.Vector3[1];
  26111. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26112. var startIndex = 0;
  26113. var originalAnimation = holder.animations[0];
  26114. var originalValue = holder.originalValue;
  26115. var scale = 1;
  26116. if (holder.totalWeight < 1.0) {
  26117. // We need to mix the original value in
  26118. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26119. scale = 1.0 - holder.totalWeight;
  26120. }
  26121. else {
  26122. startIndex = 1;
  26123. // We need to normalize the weights
  26124. normalizer = holder.totalWeight;
  26125. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26126. scale = originalAnimation.weight / normalizer;
  26127. if (scale == 1) {
  26128. return originalAnimation.currentValue;
  26129. }
  26130. }
  26131. finalScaling.scaleInPlace(scale);
  26132. finalPosition.scaleInPlace(scale);
  26133. finalQuaternion.scaleInPlace(scale);
  26134. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26135. var runtimeAnimation = holder.animations[animIndex];
  26136. var scale = runtimeAnimation.weight / normalizer;
  26137. var currentPosition = BABYLON.Tmp.Vector3[2];
  26138. var currentScaling = BABYLON.Tmp.Vector3[3];
  26139. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26140. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26141. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26142. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26143. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26144. }
  26145. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26146. return originalAnimation._workValue;
  26147. };
  26148. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26149. var originalAnimation = holder.animations[0];
  26150. var originalValue = holder.originalValue;
  26151. if (holder.animations.length === 1) {
  26152. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26153. return refQuaternion;
  26154. }
  26155. var normalizer = 1.0;
  26156. var quaternions;
  26157. var weights;
  26158. if (holder.totalWeight < 1.0) {
  26159. var scale = 1.0 - holder.totalWeight;
  26160. quaternions = [];
  26161. weights = [];
  26162. quaternions.push(originalValue);
  26163. weights.push(scale);
  26164. }
  26165. else {
  26166. if (holder.animations.length === 2) { // Slerp as soon as we can
  26167. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26168. return refQuaternion;
  26169. }
  26170. quaternions = [];
  26171. weights = [];
  26172. normalizer = holder.totalWeight;
  26173. }
  26174. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26175. var runtimeAnimation = holder.animations[animIndex];
  26176. quaternions.push(runtimeAnimation.currentValue);
  26177. weights.push(runtimeAnimation.weight / normalizer);
  26178. }
  26179. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26180. var cumulativeAmount = 0;
  26181. var cumulativeQuaternion = null;
  26182. for (var index = 0; index < quaternions.length;) {
  26183. if (!cumulativeQuaternion) {
  26184. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26185. cumulativeQuaternion = refQuaternion;
  26186. cumulativeAmount = weights[index] + weights[index + 1];
  26187. index += 2;
  26188. continue;
  26189. }
  26190. cumulativeAmount += weights[index];
  26191. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26192. index++;
  26193. }
  26194. return cumulativeQuaternion;
  26195. };
  26196. Scene.prototype._processLateAnimationBindings = function () {
  26197. if (!this._registeredForLateAnimationBindings.length) {
  26198. return;
  26199. }
  26200. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26201. var target = this._registeredForLateAnimationBindings.data[index];
  26202. for (var path in target._lateAnimationHolders) {
  26203. var holder = target._lateAnimationHolders[path];
  26204. var originalAnimation = holder.animations[0];
  26205. var originalValue = holder.originalValue;
  26206. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26207. var finalValue = target[path];
  26208. if (matrixDecomposeMode) {
  26209. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26210. }
  26211. else {
  26212. var quaternionMode = originalValue.w !== undefined;
  26213. if (quaternionMode) {
  26214. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26215. }
  26216. else {
  26217. var startIndex = 0;
  26218. var normalizer = 1.0;
  26219. if (holder.totalWeight < 1.0) {
  26220. // We need to mix the original value in
  26221. if (originalValue.scale) {
  26222. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26223. }
  26224. else {
  26225. finalValue = originalValue * (1.0 - holder.totalWeight);
  26226. }
  26227. }
  26228. else {
  26229. // We need to normalize the weights
  26230. normalizer = holder.totalWeight;
  26231. var scale_1 = originalAnimation.weight / normalizer;
  26232. if (scale_1 !== 1) {
  26233. if (originalAnimation.currentValue.scale) {
  26234. finalValue = originalAnimation.currentValue.scale(scale_1);
  26235. }
  26236. else {
  26237. finalValue = originalAnimation.currentValue * scale_1;
  26238. }
  26239. }
  26240. else {
  26241. finalValue = originalAnimation.currentValue;
  26242. }
  26243. startIndex = 1;
  26244. }
  26245. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26246. var runtimeAnimation = holder.animations[animIndex];
  26247. var scale = runtimeAnimation.weight / normalizer;
  26248. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26249. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26250. }
  26251. else {
  26252. finalValue += runtimeAnimation.currentValue * scale;
  26253. }
  26254. }
  26255. }
  26256. }
  26257. target[path] = finalValue;
  26258. }
  26259. target._lateAnimationHolders = {};
  26260. }
  26261. this._registeredForLateAnimationBindings.reset();
  26262. };
  26263. // Matrix
  26264. /** @hidden */
  26265. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26266. this._useAlternateCameraConfiguration = active;
  26267. };
  26268. /**
  26269. * Gets the current view matrix
  26270. * @returns a Matrix
  26271. */
  26272. Scene.prototype.getViewMatrix = function () {
  26273. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26274. };
  26275. /**
  26276. * Gets the current projection matrix
  26277. * @returns a Matrix
  26278. */
  26279. Scene.prototype.getProjectionMatrix = function () {
  26280. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26281. };
  26282. /**
  26283. * Gets the current transform matrix
  26284. * @returns a Matrix made of View * Projection
  26285. */
  26286. Scene.prototype.getTransformMatrix = function () {
  26287. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26288. };
  26289. /**
  26290. * Sets the current transform matrix
  26291. * @param view defines the View matrix to use
  26292. * @param projection defines the Projection matrix to use
  26293. */
  26294. Scene.prototype.setTransformMatrix = function (view, projection) {
  26295. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26296. return;
  26297. }
  26298. this._viewUpdateFlag = view.updateFlag;
  26299. this._projectionUpdateFlag = projection.updateFlag;
  26300. this._viewMatrix = view;
  26301. this._projectionMatrix = projection;
  26302. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26303. // Update frustum
  26304. if (!this._frustumPlanes) {
  26305. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26306. }
  26307. else {
  26308. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26309. }
  26310. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26311. var otherCamera = this.activeCamera._alternateCamera;
  26312. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26313. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26314. }
  26315. if (this._sceneUbo.useUbo) {
  26316. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26317. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26318. this._sceneUbo.update();
  26319. }
  26320. };
  26321. /** @hidden */
  26322. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26323. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26324. return;
  26325. }
  26326. this._alternateViewUpdateFlag = view.updateFlag;
  26327. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26328. this._alternateViewMatrix = view;
  26329. this._alternateProjectionMatrix = projection;
  26330. if (!this._alternateTransformMatrix) {
  26331. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26332. }
  26333. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26334. if (!this._alternateSceneUbo) {
  26335. this._createAlternateUbo();
  26336. }
  26337. if (this._alternateSceneUbo.useUbo) {
  26338. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26339. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26340. this._alternateSceneUbo.update();
  26341. }
  26342. };
  26343. /**
  26344. * Gets the uniform buffer used to store scene data
  26345. * @returns a UniformBuffer
  26346. */
  26347. Scene.prototype.getSceneUniformBuffer = function () {
  26348. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26349. };
  26350. /**
  26351. * Gets an unique (relatively to the current scene) Id
  26352. * @returns an unique number for the scene
  26353. */
  26354. Scene.prototype.getUniqueId = function () {
  26355. var result = Scene._uniqueIdCounter;
  26356. Scene._uniqueIdCounter++;
  26357. return result;
  26358. };
  26359. /**
  26360. * Add a mesh to the list of scene's meshes
  26361. * @param newMesh defines the mesh to add
  26362. * @param recursive if all child meshes should also be added to the scene
  26363. */
  26364. Scene.prototype.addMesh = function (newMesh, recursive) {
  26365. var _this = this;
  26366. if (recursive === void 0) { recursive = false; }
  26367. this.meshes.push(newMesh);
  26368. //notify the collision coordinator
  26369. if (this.collisionCoordinator) {
  26370. this.collisionCoordinator.onMeshAdded(newMesh);
  26371. }
  26372. newMesh._resyncLightSources();
  26373. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26374. if (recursive) {
  26375. newMesh.getChildMeshes().forEach(function (m) {
  26376. _this.addMesh(m);
  26377. });
  26378. }
  26379. };
  26380. /**
  26381. * Remove a mesh for the list of scene's meshes
  26382. * @param toRemove defines the mesh to remove
  26383. * @param recursive if all child meshes should also be removed from the scene
  26384. * @returns the index where the mesh was in the mesh list
  26385. */
  26386. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26387. var _this = this;
  26388. if (recursive === void 0) { recursive = false; }
  26389. var index = this.meshes.indexOf(toRemove);
  26390. if (index !== -1) {
  26391. // Remove from the scene if mesh found
  26392. this.meshes.splice(index, 1);
  26393. }
  26394. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26395. if (recursive) {
  26396. toRemove.getChildMeshes().forEach(function (m) {
  26397. _this.removeMesh(m);
  26398. });
  26399. }
  26400. return index;
  26401. };
  26402. /**
  26403. * Add a transform node to the list of scene's transform nodes
  26404. * @param newTransformNode defines the transform node to add
  26405. */
  26406. Scene.prototype.addTransformNode = function (newTransformNode) {
  26407. this.transformNodes.push(newTransformNode);
  26408. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26409. };
  26410. /**
  26411. * Remove a transform node for the list of scene's transform nodes
  26412. * @param toRemove defines the transform node to remove
  26413. * @returns the index where the transform node was in the transform node list
  26414. */
  26415. Scene.prototype.removeTransformNode = function (toRemove) {
  26416. var index = this.transformNodes.indexOf(toRemove);
  26417. if (index !== -1) {
  26418. // Remove from the scene if found
  26419. this.transformNodes.splice(index, 1);
  26420. }
  26421. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26422. return index;
  26423. };
  26424. /**
  26425. * Remove a skeleton for the list of scene's skeletons
  26426. * @param toRemove defines the skeleton to remove
  26427. * @returns the index where the skeleton was in the skeleton list
  26428. */
  26429. Scene.prototype.removeSkeleton = function (toRemove) {
  26430. var index = this.skeletons.indexOf(toRemove);
  26431. if (index !== -1) {
  26432. // Remove from the scene if found
  26433. this.skeletons.splice(index, 1);
  26434. }
  26435. return index;
  26436. };
  26437. /**
  26438. * Remove a morph target for the list of scene's morph targets
  26439. * @param toRemove defines the morph target to remove
  26440. * @returns the index where the morph target was in the morph target list
  26441. */
  26442. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26443. var index = this.morphTargetManagers.indexOf(toRemove);
  26444. if (index !== -1) {
  26445. // Remove from the scene if found
  26446. this.morphTargetManagers.splice(index, 1);
  26447. }
  26448. return index;
  26449. };
  26450. /**
  26451. * Remove a light for the list of scene's lights
  26452. * @param toRemove defines the light to remove
  26453. * @returns the index where the light was in the light list
  26454. */
  26455. Scene.prototype.removeLight = function (toRemove) {
  26456. var index = this.lights.indexOf(toRemove);
  26457. if (index !== -1) {
  26458. // Remove from meshes
  26459. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26460. var mesh = _a[_i];
  26461. mesh._removeLightSource(toRemove);
  26462. }
  26463. // Remove from the scene if mesh found
  26464. this.lights.splice(index, 1);
  26465. this.sortLightsByPriority();
  26466. }
  26467. this.onLightRemovedObservable.notifyObservers(toRemove);
  26468. return index;
  26469. };
  26470. /**
  26471. * Remove a camera for the list of scene's cameras
  26472. * @param toRemove defines the camera to remove
  26473. * @returns the index where the camera was in the camera list
  26474. */
  26475. Scene.prototype.removeCamera = function (toRemove) {
  26476. var index = this.cameras.indexOf(toRemove);
  26477. if (index !== -1) {
  26478. // Remove from the scene if mesh found
  26479. this.cameras.splice(index, 1);
  26480. }
  26481. // Remove from activeCameras
  26482. var index2 = this.activeCameras.indexOf(toRemove);
  26483. if (index2 !== -1) {
  26484. // Remove from the scene if mesh found
  26485. this.activeCameras.splice(index2, 1);
  26486. }
  26487. // Reset the activeCamera
  26488. if (this.activeCamera === toRemove) {
  26489. if (this.cameras.length > 0) {
  26490. this.activeCamera = this.cameras[0];
  26491. }
  26492. else {
  26493. this.activeCamera = null;
  26494. }
  26495. }
  26496. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26497. return index;
  26498. };
  26499. /**
  26500. * Remove a particle system for the list of scene's particle systems
  26501. * @param toRemove defines the particle system to remove
  26502. * @returns the index where the particle system was in the particle system list
  26503. */
  26504. Scene.prototype.removeParticleSystem = function (toRemove) {
  26505. var index = this.particleSystems.indexOf(toRemove);
  26506. if (index !== -1) {
  26507. this.particleSystems.splice(index, 1);
  26508. }
  26509. return index;
  26510. };
  26511. /**
  26512. * Remove a animation for the list of scene's animations
  26513. * @param toRemove defines the animation to remove
  26514. * @returns the index where the animation was in the animation list
  26515. */
  26516. Scene.prototype.removeAnimation = function (toRemove) {
  26517. var index = this.animations.indexOf(toRemove);
  26518. if (index !== -1) {
  26519. this.animations.splice(index, 1);
  26520. }
  26521. return index;
  26522. };
  26523. /**
  26524. * Removes the given animation group from this scene.
  26525. * @param toRemove The animation group to remove
  26526. * @returns The index of the removed animation group
  26527. */
  26528. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26529. var index = this.animationGroups.indexOf(toRemove);
  26530. if (index !== -1) {
  26531. this.animationGroups.splice(index, 1);
  26532. }
  26533. return index;
  26534. };
  26535. /**
  26536. * Removes the given multi-material from this scene.
  26537. * @param toRemove The multi-material to remove
  26538. * @returns The index of the removed multi-material
  26539. */
  26540. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26541. var index = this.multiMaterials.indexOf(toRemove);
  26542. if (index !== -1) {
  26543. this.multiMaterials.splice(index, 1);
  26544. }
  26545. return index;
  26546. };
  26547. /**
  26548. * Removes the given material from this scene.
  26549. * @param toRemove The material to remove
  26550. * @returns The index of the removed material
  26551. */
  26552. Scene.prototype.removeMaterial = function (toRemove) {
  26553. var index = this.materials.indexOf(toRemove);
  26554. if (index !== -1) {
  26555. this.materials.splice(index, 1);
  26556. }
  26557. return index;
  26558. };
  26559. /**
  26560. * Removes the given action manager from this scene.
  26561. * @param toRemove The action manager to remove
  26562. * @returns The index of the removed action manager
  26563. */
  26564. Scene.prototype.removeActionManager = function (toRemove) {
  26565. var index = this.actionManagers.indexOf(toRemove);
  26566. if (index !== -1) {
  26567. this.actionManagers.splice(index, 1);
  26568. }
  26569. return index;
  26570. };
  26571. /**
  26572. * Removes the given texture from this scene.
  26573. * @param toRemove The texture to remove
  26574. * @returns The index of the removed texture
  26575. */
  26576. Scene.prototype.removeTexture = function (toRemove) {
  26577. var index = this.textures.indexOf(toRemove);
  26578. if (index !== -1) {
  26579. this.textures.splice(index, 1);
  26580. }
  26581. return index;
  26582. };
  26583. /**
  26584. * Adds the given light to this scene
  26585. * @param newLight The light to add
  26586. */
  26587. Scene.prototype.addLight = function (newLight) {
  26588. this.lights.push(newLight);
  26589. this.sortLightsByPriority();
  26590. // Add light to all meshes (To support if the light is removed and then readded)
  26591. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26592. var mesh = _a[_i];
  26593. if (mesh._lightSources.indexOf(newLight) === -1) {
  26594. mesh._lightSources.push(newLight);
  26595. mesh._resyncLightSources();
  26596. }
  26597. }
  26598. this.onNewLightAddedObservable.notifyObservers(newLight);
  26599. };
  26600. /**
  26601. * Sorts the list list based on light priorities
  26602. */
  26603. Scene.prototype.sortLightsByPriority = function () {
  26604. if (this.requireLightSorting) {
  26605. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26606. }
  26607. };
  26608. /**
  26609. * Adds the given camera to this scene
  26610. * @param newCamera The camera to add
  26611. */
  26612. Scene.prototype.addCamera = function (newCamera) {
  26613. this.cameras.push(newCamera);
  26614. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26615. };
  26616. /**
  26617. * Adds the given skeleton to this scene
  26618. * @param newSkeleton The skeleton to add
  26619. */
  26620. Scene.prototype.addSkeleton = function (newSkeleton) {
  26621. this.skeletons.push(newSkeleton);
  26622. };
  26623. /**
  26624. * Adds the given particle system to this scene
  26625. * @param newParticleSystem The particle system to add
  26626. */
  26627. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26628. this.particleSystems.push(newParticleSystem);
  26629. };
  26630. /**
  26631. * Adds the given animation to this scene
  26632. * @param newAnimation The animation to add
  26633. */
  26634. Scene.prototype.addAnimation = function (newAnimation) {
  26635. this.animations.push(newAnimation);
  26636. };
  26637. /**
  26638. * Adds the given animation group to this scene.
  26639. * @param newAnimationGroup The animation group to add
  26640. */
  26641. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26642. this.animationGroups.push(newAnimationGroup);
  26643. };
  26644. /**
  26645. * Adds the given multi-material to this scene
  26646. * @param newMultiMaterial The multi-material to add
  26647. */
  26648. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26649. this.multiMaterials.push(newMultiMaterial);
  26650. };
  26651. /**
  26652. * Adds the given material to this scene
  26653. * @param newMaterial The material to add
  26654. */
  26655. Scene.prototype.addMaterial = function (newMaterial) {
  26656. this.materials.push(newMaterial);
  26657. };
  26658. /**
  26659. * Adds the given morph target to this scene
  26660. * @param newMorphTargetManager The morph target to add
  26661. */
  26662. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26663. this.morphTargetManagers.push(newMorphTargetManager);
  26664. };
  26665. /**
  26666. * Adds the given geometry to this scene
  26667. * @param newGeometry The geometry to add
  26668. */
  26669. Scene.prototype.addGeometry = function (newGeometry) {
  26670. this.geometries.push(newGeometry);
  26671. };
  26672. /**
  26673. * Adds the given action manager to this scene
  26674. * @param newActionManager The action manager to add
  26675. */
  26676. Scene.prototype.addActionManager = function (newActionManager) {
  26677. this.actionManagers.push(newActionManager);
  26678. };
  26679. /**
  26680. * Adds the given texture to this scene.
  26681. * @param newTexture The texture to add
  26682. */
  26683. Scene.prototype.addTexture = function (newTexture) {
  26684. this.textures.push(newTexture);
  26685. };
  26686. /**
  26687. * Switch active camera
  26688. * @param newCamera defines the new active camera
  26689. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26690. */
  26691. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26692. if (attachControl === void 0) { attachControl = true; }
  26693. var canvas = this._engine.getRenderingCanvas();
  26694. if (!canvas) {
  26695. return;
  26696. }
  26697. if (this.activeCamera) {
  26698. this.activeCamera.detachControl(canvas);
  26699. }
  26700. this.activeCamera = newCamera;
  26701. if (attachControl) {
  26702. newCamera.attachControl(canvas);
  26703. }
  26704. };
  26705. /**
  26706. * sets the active camera of the scene using its ID
  26707. * @param id defines the camera's ID
  26708. * @return the new active camera or null if none found.
  26709. */
  26710. Scene.prototype.setActiveCameraByID = function (id) {
  26711. var camera = this.getCameraByID(id);
  26712. if (camera) {
  26713. this.activeCamera = camera;
  26714. return camera;
  26715. }
  26716. return null;
  26717. };
  26718. /**
  26719. * sets the active camera of the scene using its name
  26720. * @param name defines the camera's name
  26721. * @returns the new active camera or null if none found.
  26722. */
  26723. Scene.prototype.setActiveCameraByName = function (name) {
  26724. var camera = this.getCameraByName(name);
  26725. if (camera) {
  26726. this.activeCamera = camera;
  26727. return camera;
  26728. }
  26729. return null;
  26730. };
  26731. /**
  26732. * get an animation group using its name
  26733. * @param name defines the material's name
  26734. * @return the animation group or null if none found.
  26735. */
  26736. Scene.prototype.getAnimationGroupByName = function (name) {
  26737. for (var index = 0; index < this.animationGroups.length; index++) {
  26738. if (this.animationGroups[index].name === name) {
  26739. return this.animationGroups[index];
  26740. }
  26741. }
  26742. return null;
  26743. };
  26744. /**
  26745. * get a material using its id
  26746. * @param id defines the material's ID
  26747. * @return the material or null if none found.
  26748. */
  26749. Scene.prototype.getMaterialByID = function (id) {
  26750. for (var index = 0; index < this.materials.length; index++) {
  26751. if (this.materials[index].id === id) {
  26752. return this.materials[index];
  26753. }
  26754. }
  26755. return null;
  26756. };
  26757. /**
  26758. * Gets a material using its name
  26759. * @param name defines the material's name
  26760. * @return the material or null if none found.
  26761. */
  26762. Scene.prototype.getMaterialByName = function (name) {
  26763. for (var index = 0; index < this.materials.length; index++) {
  26764. if (this.materials[index].name === name) {
  26765. return this.materials[index];
  26766. }
  26767. }
  26768. return null;
  26769. };
  26770. /**
  26771. * Gets a camera using its id
  26772. * @param id defines the id to look for
  26773. * @returns the camera or null if not found
  26774. */
  26775. Scene.prototype.getCameraByID = function (id) {
  26776. for (var index = 0; index < this.cameras.length; index++) {
  26777. if (this.cameras[index].id === id) {
  26778. return this.cameras[index];
  26779. }
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * Gets a camera using its unique id
  26785. * @param uniqueId defines the unique id to look for
  26786. * @returns the camera or null if not found
  26787. */
  26788. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26789. for (var index = 0; index < this.cameras.length; index++) {
  26790. if (this.cameras[index].uniqueId === uniqueId) {
  26791. return this.cameras[index];
  26792. }
  26793. }
  26794. return null;
  26795. };
  26796. /**
  26797. * Gets a camera using its name
  26798. * @param name defines the camera's name
  26799. * @return the camera or null if none found.
  26800. */
  26801. Scene.prototype.getCameraByName = function (name) {
  26802. for (var index = 0; index < this.cameras.length; index++) {
  26803. if (this.cameras[index].name === name) {
  26804. return this.cameras[index];
  26805. }
  26806. }
  26807. return null;
  26808. };
  26809. /**
  26810. * Gets a bone using its id
  26811. * @param id defines the bone's id
  26812. * @return the bone or null if not found
  26813. */
  26814. Scene.prototype.getBoneByID = function (id) {
  26815. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26816. var skeleton = this.skeletons[skeletonIndex];
  26817. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26818. if (skeleton.bones[boneIndex].id === id) {
  26819. return skeleton.bones[boneIndex];
  26820. }
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a bone using its id
  26827. * @param name defines the bone's name
  26828. * @return the bone or null if not found
  26829. */
  26830. Scene.prototype.getBoneByName = function (name) {
  26831. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26832. var skeleton = this.skeletons[skeletonIndex];
  26833. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26834. if (skeleton.bones[boneIndex].name === name) {
  26835. return skeleton.bones[boneIndex];
  26836. }
  26837. }
  26838. }
  26839. return null;
  26840. };
  26841. /**
  26842. * Gets a light node using its name
  26843. * @param name defines the the light's name
  26844. * @return the light or null if none found.
  26845. */
  26846. Scene.prototype.getLightByName = function (name) {
  26847. for (var index = 0; index < this.lights.length; index++) {
  26848. if (this.lights[index].name === name) {
  26849. return this.lights[index];
  26850. }
  26851. }
  26852. return null;
  26853. };
  26854. /**
  26855. * Gets a light node using its id
  26856. * @param id defines the light's id
  26857. * @return the light or null if none found.
  26858. */
  26859. Scene.prototype.getLightByID = function (id) {
  26860. for (var index = 0; index < this.lights.length; index++) {
  26861. if (this.lights[index].id === id) {
  26862. return this.lights[index];
  26863. }
  26864. }
  26865. return null;
  26866. };
  26867. /**
  26868. * Gets a light node using its scene-generated unique ID
  26869. * @param uniqueId defines the light's unique id
  26870. * @return the light or null if none found.
  26871. */
  26872. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26873. for (var index = 0; index < this.lights.length; index++) {
  26874. if (this.lights[index].uniqueId === uniqueId) {
  26875. return this.lights[index];
  26876. }
  26877. }
  26878. return null;
  26879. };
  26880. /**
  26881. * Gets a particle system by id
  26882. * @param id defines the particle system id
  26883. * @return the corresponding system or null if none found
  26884. */
  26885. Scene.prototype.getParticleSystemByID = function (id) {
  26886. for (var index = 0; index < this.particleSystems.length; index++) {
  26887. if (this.particleSystems[index].id === id) {
  26888. return this.particleSystems[index];
  26889. }
  26890. }
  26891. return null;
  26892. };
  26893. /**
  26894. * Gets a geometry using its ID
  26895. * @param id defines the geometry's id
  26896. * @return the geometry or null if none found.
  26897. */
  26898. Scene.prototype.getGeometryByID = function (id) {
  26899. for (var index = 0; index < this.geometries.length; index++) {
  26900. if (this.geometries[index].id === id) {
  26901. return this.geometries[index];
  26902. }
  26903. }
  26904. return null;
  26905. };
  26906. /**
  26907. * Add a new geometry to this scene
  26908. * @param geometry defines the geometry to be added to the scene.
  26909. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26910. * @return a boolean defining if the geometry was added or not
  26911. */
  26912. Scene.prototype.pushGeometry = function (geometry, force) {
  26913. if (!force && this.getGeometryByID(geometry.id)) {
  26914. return false;
  26915. }
  26916. this.geometries.push(geometry);
  26917. //notify the collision coordinator
  26918. if (this.collisionCoordinator) {
  26919. this.collisionCoordinator.onGeometryAdded(geometry);
  26920. }
  26921. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26922. return true;
  26923. };
  26924. /**
  26925. * Removes an existing geometry
  26926. * @param geometry defines the geometry to be removed from the scene
  26927. * @return a boolean defining if the geometry was removed or not
  26928. */
  26929. Scene.prototype.removeGeometry = function (geometry) {
  26930. var index = this.geometries.indexOf(geometry);
  26931. if (index > -1) {
  26932. this.geometries.splice(index, 1);
  26933. //notify the collision coordinator
  26934. if (this.collisionCoordinator) {
  26935. this.collisionCoordinator.onGeometryDeleted(geometry);
  26936. }
  26937. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26938. return true;
  26939. }
  26940. return false;
  26941. };
  26942. /**
  26943. * Gets the list of geometries attached to the scene
  26944. * @returns an array of Geometry
  26945. */
  26946. Scene.prototype.getGeometries = function () {
  26947. return this.geometries;
  26948. };
  26949. /**
  26950. * Gets the first added mesh found of a given ID
  26951. * @param id defines the id to search for
  26952. * @return the mesh found or null if not found at all
  26953. */
  26954. Scene.prototype.getMeshByID = function (id) {
  26955. for (var index = 0; index < this.meshes.length; index++) {
  26956. if (this.meshes[index].id === id) {
  26957. return this.meshes[index];
  26958. }
  26959. }
  26960. return null;
  26961. };
  26962. /**
  26963. * Gets a list of meshes using their id
  26964. * @param id defines the id to search for
  26965. * @returns a list of meshes
  26966. */
  26967. Scene.prototype.getMeshesByID = function (id) {
  26968. return this.meshes.filter(function (m) {
  26969. return m.id === id;
  26970. });
  26971. };
  26972. /**
  26973. * Gets the first added transform node found of a given ID
  26974. * @param id defines the id to search for
  26975. * @return the found transform node or null if not found at all.
  26976. */
  26977. Scene.prototype.getTransformNodeByID = function (id) {
  26978. for (var index = 0; index < this.transformNodes.length; index++) {
  26979. if (this.transformNodes[index].id === id) {
  26980. return this.transformNodes[index];
  26981. }
  26982. }
  26983. return null;
  26984. };
  26985. /**
  26986. * Gets a list of transform nodes using their id
  26987. * @param id defines the id to search for
  26988. * @returns a list of transform nodes
  26989. */
  26990. Scene.prototype.getTransformNodesByID = function (id) {
  26991. return this.transformNodes.filter(function (m) {
  26992. return m.id === id;
  26993. });
  26994. };
  26995. /**
  26996. * Gets a mesh with its auto-generated unique id
  26997. * @param uniqueId defines the unique id to search for
  26998. * @return the found mesh or null if not found at all.
  26999. */
  27000. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27001. for (var index = 0; index < this.meshes.length; index++) {
  27002. if (this.meshes[index].uniqueId === uniqueId) {
  27003. return this.meshes[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Gets a the last added mesh using a given id
  27010. * @param id defines the id to search for
  27011. * @return the found mesh or null if not found at all.
  27012. */
  27013. Scene.prototype.getLastMeshByID = function (id) {
  27014. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27015. if (this.meshes[index].id === id) {
  27016. return this.meshes[index];
  27017. }
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27023. * @param id defines the id to search for
  27024. * @return the found node or null if not found at all
  27025. */
  27026. Scene.prototype.getLastEntryByID = function (id) {
  27027. var index;
  27028. for (index = this.meshes.length - 1; index >= 0; index--) {
  27029. if (this.meshes[index].id === id) {
  27030. return this.meshes[index];
  27031. }
  27032. }
  27033. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27034. if (this.transformNodes[index].id === id) {
  27035. return this.transformNodes[index];
  27036. }
  27037. }
  27038. for (index = this.cameras.length - 1; index >= 0; index--) {
  27039. if (this.cameras[index].id === id) {
  27040. return this.cameras[index];
  27041. }
  27042. }
  27043. for (index = this.lights.length - 1; index >= 0; index--) {
  27044. if (this.lights[index].id === id) {
  27045. return this.lights[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a node (Mesh, Camera, Light) using a given id
  27052. * @param id defines the id to search for
  27053. * @return the found node or null if not found at all
  27054. */
  27055. Scene.prototype.getNodeByID = function (id) {
  27056. var mesh = this.getMeshByID(id);
  27057. if (mesh) {
  27058. return mesh;
  27059. }
  27060. var light = this.getLightByID(id);
  27061. if (light) {
  27062. return light;
  27063. }
  27064. var camera = this.getCameraByID(id);
  27065. if (camera) {
  27066. return camera;
  27067. }
  27068. var bone = this.getBoneByID(id);
  27069. return bone;
  27070. };
  27071. /**
  27072. * Gets a node (Mesh, Camera, Light) using a given name
  27073. * @param name defines the name to search for
  27074. * @return the found node or null if not found at all.
  27075. */
  27076. Scene.prototype.getNodeByName = function (name) {
  27077. var mesh = this.getMeshByName(name);
  27078. if (mesh) {
  27079. return mesh;
  27080. }
  27081. var light = this.getLightByName(name);
  27082. if (light) {
  27083. return light;
  27084. }
  27085. var camera = this.getCameraByName(name);
  27086. if (camera) {
  27087. return camera;
  27088. }
  27089. var bone = this.getBoneByName(name);
  27090. return bone;
  27091. };
  27092. /**
  27093. * Gets a mesh using a given name
  27094. * @param name defines the name to search for
  27095. * @return the found mesh or null if not found at all.
  27096. */
  27097. Scene.prototype.getMeshByName = function (name) {
  27098. for (var index = 0; index < this.meshes.length; index++) {
  27099. if (this.meshes[index].name === name) {
  27100. return this.meshes[index];
  27101. }
  27102. }
  27103. return null;
  27104. };
  27105. /**
  27106. * Gets a transform node using a given name
  27107. * @param name defines the name to search for
  27108. * @return the found transform node or null if not found at all.
  27109. */
  27110. Scene.prototype.getTransformNodeByName = function (name) {
  27111. for (var index = 0; index < this.transformNodes.length; index++) {
  27112. if (this.transformNodes[index].name === name) {
  27113. return this.transformNodes[index];
  27114. }
  27115. }
  27116. return null;
  27117. };
  27118. /**
  27119. * Gets a sound using a given name
  27120. * @param name defines the name to search for
  27121. * @return the found sound or null if not found at all.
  27122. */
  27123. Scene.prototype.getSoundByName = function (name) {
  27124. var index;
  27125. if (BABYLON.AudioEngine) {
  27126. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27127. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27128. return this.mainSoundTrack.soundCollection[index];
  27129. }
  27130. }
  27131. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27132. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27133. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27134. return this.soundTracks[sdIndex].soundCollection[index];
  27135. }
  27136. }
  27137. }
  27138. }
  27139. return null;
  27140. };
  27141. /**
  27142. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27143. * @param id defines the id to search for
  27144. * @return the found skeleton or null if not found at all.
  27145. */
  27146. Scene.prototype.getLastSkeletonByID = function (id) {
  27147. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27148. if (this.skeletons[index].id === id) {
  27149. return this.skeletons[index];
  27150. }
  27151. }
  27152. return null;
  27153. };
  27154. /**
  27155. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27156. * @param id defines the id to search for
  27157. * @return the found skeleton or null if not found at all.
  27158. */
  27159. Scene.prototype.getSkeletonById = function (id) {
  27160. for (var index = 0; index < this.skeletons.length; index++) {
  27161. if (this.skeletons[index].id === id) {
  27162. return this.skeletons[index];
  27163. }
  27164. }
  27165. return null;
  27166. };
  27167. /**
  27168. * Gets a skeleton using a given name
  27169. * @param name defines the name to search for
  27170. * @return the found skeleton or null if not found at all.
  27171. */
  27172. Scene.prototype.getSkeletonByName = function (name) {
  27173. for (var index = 0; index < this.skeletons.length; index++) {
  27174. if (this.skeletons[index].name === name) {
  27175. return this.skeletons[index];
  27176. }
  27177. }
  27178. return null;
  27179. };
  27180. /**
  27181. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27182. * @param id defines the id to search for
  27183. * @return the found morph target manager or null if not found at all.
  27184. */
  27185. Scene.prototype.getMorphTargetManagerById = function (id) {
  27186. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27187. if (this.morphTargetManagers[index].uniqueId === id) {
  27188. return this.morphTargetManagers[index];
  27189. }
  27190. }
  27191. return null;
  27192. };
  27193. /**
  27194. * Gets a boolean indicating if the given mesh is active
  27195. * @param mesh defines the mesh to look for
  27196. * @returns true if the mesh is in the active list
  27197. */
  27198. Scene.prototype.isActiveMesh = function (mesh) {
  27199. return (this._activeMeshes.indexOf(mesh) !== -1);
  27200. };
  27201. Object.defineProperty(Scene.prototype, "uid", {
  27202. /**
  27203. * Return a unique id as a string which can serve as an identifier for the scene
  27204. */
  27205. get: function () {
  27206. if (!this._uid) {
  27207. this._uid = BABYLON.Tools.RandomId();
  27208. }
  27209. return this._uid;
  27210. },
  27211. enumerable: true,
  27212. configurable: true
  27213. });
  27214. /**
  27215. * Add an externaly attached data from its key.
  27216. * This method call will fail and return false, if such key already exists.
  27217. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27218. * @param key the unique key that identifies the data
  27219. * @param data the data object to associate to the key for this Engine instance
  27220. * @return true if no such key were already present and the data was added successfully, false otherwise
  27221. */
  27222. Scene.prototype.addExternalData = function (key, data) {
  27223. if (!this._externalData) {
  27224. this._externalData = new BABYLON.StringDictionary();
  27225. }
  27226. return this._externalData.add(key, data);
  27227. };
  27228. /**
  27229. * Get an externaly attached data from its key
  27230. * @param key the unique key that identifies the data
  27231. * @return the associated data, if present (can be null), or undefined if not present
  27232. */
  27233. Scene.prototype.getExternalData = function (key) {
  27234. if (!this._externalData) {
  27235. return null;
  27236. }
  27237. return this._externalData.get(key);
  27238. };
  27239. /**
  27240. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27241. * @param key the unique key that identifies the data
  27242. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27243. * @return the associated data, can be null if the factory returned null.
  27244. */
  27245. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27246. if (!this._externalData) {
  27247. this._externalData = new BABYLON.StringDictionary();
  27248. }
  27249. return this._externalData.getOrAddWithFactory(key, factory);
  27250. };
  27251. /**
  27252. * Remove an externaly attached data from the Engine instance
  27253. * @param key the unique key that identifies the data
  27254. * @return true if the data was successfully removed, false if it doesn't exist
  27255. */
  27256. Scene.prototype.removeExternalData = function (key) {
  27257. return this._externalData.remove(key);
  27258. };
  27259. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27260. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27261. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27262. var step = _a[_i];
  27263. step.action(mesh, subMesh);
  27264. }
  27265. var material = subMesh.getMaterial();
  27266. if (material !== null && material !== undefined) {
  27267. // Render targets
  27268. if (material.getRenderTargetTextures !== undefined) {
  27269. if (this._processedMaterials.indexOf(material) === -1) {
  27270. this._processedMaterials.push(material);
  27271. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27272. }
  27273. }
  27274. // Dispatch
  27275. this._activeIndices.addCount(subMesh.indexCount, false);
  27276. this._renderingManager.dispatch(subMesh, mesh, material);
  27277. }
  27278. }
  27279. };
  27280. /**
  27281. * Clear the processed materials smart array preventing retention point in material dispose.
  27282. */
  27283. Scene.prototype.freeProcessedMaterials = function () {
  27284. this._processedMaterials.dispose();
  27285. };
  27286. /**
  27287. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27288. */
  27289. Scene.prototype.freeActiveMeshes = function () {
  27290. this._activeMeshes.dispose();
  27291. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27292. this.activeCamera._activeMeshes.dispose();
  27293. }
  27294. if (this.activeCameras) {
  27295. for (var i = 0; i < this.activeCameras.length; i++) {
  27296. var activeCamera = this.activeCameras[i];
  27297. if (activeCamera && activeCamera._activeMeshes) {
  27298. activeCamera._activeMeshes.dispose();
  27299. }
  27300. }
  27301. }
  27302. };
  27303. /**
  27304. * Clear the info related to rendering groups preventing retention points during dispose.
  27305. */
  27306. Scene.prototype.freeRenderingGroups = function () {
  27307. if (this._renderingManager) {
  27308. this._renderingManager.freeRenderingGroups();
  27309. }
  27310. if (this.textures) {
  27311. for (var i = 0; i < this.textures.length; i++) {
  27312. var texture = this.textures[i];
  27313. if (texture && texture.renderList) {
  27314. texture.freeRenderingGroups();
  27315. }
  27316. }
  27317. }
  27318. };
  27319. /** @hidden */
  27320. Scene.prototype._isInIntermediateRendering = function () {
  27321. return this._intermediateRendering;
  27322. };
  27323. /**
  27324. * Defines the current active mesh candidate provider
  27325. * @param provider defines the provider to use
  27326. */
  27327. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27328. this._activeMeshCandidateProvider = provider;
  27329. };
  27330. /**
  27331. * Gets the current active mesh candidate provider
  27332. * @returns the current active mesh candidate provider
  27333. */
  27334. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27335. return this._activeMeshCandidateProvider;
  27336. };
  27337. /**
  27338. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27339. * @returns the current scene
  27340. */
  27341. Scene.prototype.freezeActiveMeshes = function () {
  27342. if (!this.activeCamera) {
  27343. return this;
  27344. }
  27345. if (!this._frustumPlanes) {
  27346. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27347. }
  27348. this._evaluateActiveMeshes();
  27349. this._activeMeshesFrozen = true;
  27350. return this;
  27351. };
  27352. /**
  27353. * Use this function to restart evaluating active meshes on every frame
  27354. * @returns the current scene
  27355. */
  27356. Scene.prototype.unfreezeActiveMeshes = function () {
  27357. this._activeMeshesFrozen = false;
  27358. return this;
  27359. };
  27360. Scene.prototype._evaluateActiveMeshes = function () {
  27361. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27362. return;
  27363. }
  27364. if (!this.activeCamera) {
  27365. return;
  27366. }
  27367. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27368. this.activeCamera._activeMeshes.reset();
  27369. this._activeMeshes.reset();
  27370. this._renderingManager.reset();
  27371. this._processedMaterials.reset();
  27372. this._activeParticleSystems.reset();
  27373. this._activeSkeletons.reset();
  27374. this._softwareSkinnedMeshes.reset();
  27375. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27376. var step = _a[_i];
  27377. step.action();
  27378. }
  27379. // Meshes
  27380. var meshes;
  27381. var len;
  27382. var checkIsEnabled = true;
  27383. // Determine mesh candidates
  27384. if (this._activeMeshCandidateProvider !== undefined) {
  27385. // Use _activeMeshCandidateProvider
  27386. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27387. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27388. if (meshes !== undefined) {
  27389. len = meshes.length;
  27390. }
  27391. else {
  27392. len = 0;
  27393. }
  27394. }
  27395. else if (this._selectionOctree !== undefined) {
  27396. // Octree
  27397. var selection = this._selectionOctree.select(this._frustumPlanes);
  27398. meshes = selection.data;
  27399. len = selection.length;
  27400. }
  27401. else {
  27402. // Full scene traversal
  27403. len = this.meshes.length;
  27404. meshes = this.meshes;
  27405. }
  27406. // Check each mesh
  27407. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27408. mesh = meshes[meshIndex];
  27409. if (mesh.isBlocked) {
  27410. continue;
  27411. }
  27412. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27413. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27414. continue;
  27415. }
  27416. mesh.computeWorldMatrix();
  27417. // Intersections
  27418. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27419. this._meshesForIntersections.pushNoDuplicate(mesh);
  27420. }
  27421. // Switch to current LOD
  27422. meshLOD = mesh.getLOD(this.activeCamera);
  27423. if (meshLOD === undefined || meshLOD === null) {
  27424. continue;
  27425. }
  27426. mesh._preActivate();
  27427. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27428. this._activeMeshes.push(mesh);
  27429. this.activeCamera._activeMeshes.push(mesh);
  27430. mesh._activate(this._renderId);
  27431. if (meshLOD !== mesh) {
  27432. meshLOD._activate(this._renderId);
  27433. }
  27434. this._activeMesh(mesh, meshLOD);
  27435. }
  27436. }
  27437. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27438. // Particle systems
  27439. if (this.particlesEnabled) {
  27440. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27441. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27442. var particleSystem = this.particleSystems[particleIndex];
  27443. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27444. continue;
  27445. }
  27446. var emitter = particleSystem.emitter;
  27447. if (!emitter.position || emitter.isEnabled()) {
  27448. this._activeParticleSystems.push(particleSystem);
  27449. particleSystem.animate();
  27450. this._renderingManager.dispatchParticles(particleSystem);
  27451. }
  27452. }
  27453. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27454. }
  27455. };
  27456. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27457. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27458. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27459. mesh.skeleton.prepare();
  27460. }
  27461. if (!mesh.computeBonesUsingShaders) {
  27462. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27463. }
  27464. }
  27465. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27466. var step = _a[_i];
  27467. step.action(sourceMesh, mesh);
  27468. }
  27469. if (mesh !== undefined && mesh !== null
  27470. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27471. // Submeshes Octrees
  27472. var len;
  27473. var subMeshes;
  27474. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27475. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27476. len = intersections.length;
  27477. subMeshes = intersections.data;
  27478. }
  27479. else {
  27480. subMeshes = mesh.subMeshes;
  27481. len = subMeshes.length;
  27482. }
  27483. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27484. subMesh = subMeshes[subIndex];
  27485. this._evaluateSubMesh(subMesh, mesh);
  27486. }
  27487. }
  27488. };
  27489. /**
  27490. * Update the transform matrix to update from the current active camera
  27491. * @param force defines a boolean used to force the update even if cache is up to date
  27492. */
  27493. Scene.prototype.updateTransformMatrix = function (force) {
  27494. if (!this.activeCamera) {
  27495. return;
  27496. }
  27497. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27498. };
  27499. /**
  27500. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27501. * @param alternateCamera defines the camera to use
  27502. */
  27503. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27504. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27505. };
  27506. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27507. if (camera && camera._skipRendering) {
  27508. return;
  27509. }
  27510. var engine = this._engine;
  27511. this.activeCamera = camera;
  27512. if (!this.activeCamera)
  27513. throw new Error("Active camera not set");
  27514. // Viewport
  27515. engine.setViewport(this.activeCamera.viewport);
  27516. // Camera
  27517. this.resetCachedMaterial();
  27518. this._renderId++;
  27519. this.updateTransformMatrix();
  27520. if (camera._alternateCamera) {
  27521. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27522. this._alternateRendering = true;
  27523. }
  27524. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27525. // Meshes
  27526. this._evaluateActiveMeshes();
  27527. // Software skinning
  27528. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27529. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27530. mesh.applySkeleton(mesh.skeleton);
  27531. }
  27532. // Render targets
  27533. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27534. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27535. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27536. }
  27537. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27538. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27539. }
  27540. if (this.renderTargetsEnabled) {
  27541. this._intermediateRendering = true;
  27542. if (this._renderTargets.length > 0) {
  27543. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27544. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27545. var renderTarget = this._renderTargets.data[renderIndex];
  27546. if (renderTarget._shouldRender()) {
  27547. this._renderId++;
  27548. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27549. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27550. }
  27551. }
  27552. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27553. this._renderId++;
  27554. }
  27555. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27556. var step = _a[_i];
  27557. step.action(this.activeCamera);
  27558. }
  27559. this._intermediateRendering = false;
  27560. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27561. }
  27562. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27563. // Prepare Frame
  27564. if (this.postProcessManager) {
  27565. this.postProcessManager._prepareFrame();
  27566. }
  27567. // Before Camera Draw
  27568. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27569. var step = _c[_b];
  27570. step.action(this.activeCamera);
  27571. }
  27572. // Render
  27573. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27574. this._renderingManager.render(null, null, true, true);
  27575. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27576. // After Camera Draw
  27577. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27578. var step = _e[_d];
  27579. step.action(this.activeCamera);
  27580. }
  27581. // Finalize frame
  27582. if (this.postProcessManager) {
  27583. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27584. }
  27585. // Reset some special arrays
  27586. this._renderTargets.reset();
  27587. this._alternateRendering = false;
  27588. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27589. };
  27590. Scene.prototype._processSubCameras = function (camera) {
  27591. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27592. this._renderForCamera(camera);
  27593. return;
  27594. }
  27595. // rig cameras
  27596. for (var index = 0; index < camera._rigCameras.length; index++) {
  27597. this._renderForCamera(camera._rigCameras[index], camera);
  27598. }
  27599. this.activeCamera = camera;
  27600. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27601. };
  27602. Scene.prototype._checkIntersections = function () {
  27603. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27604. var sourceMesh = this._meshesForIntersections.data[index];
  27605. if (!sourceMesh.actionManager) {
  27606. continue;
  27607. }
  27608. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27609. var action = sourceMesh.actionManager.actions[actionIndex];
  27610. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27611. var parameters = action.getTriggerParameter();
  27612. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27613. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27614. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27615. if (areIntersecting && currentIntersectionInProgress === -1) {
  27616. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27617. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27618. sourceMesh._intersectionsInProgress.push(otherMesh);
  27619. }
  27620. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27621. sourceMesh._intersectionsInProgress.push(otherMesh);
  27622. }
  27623. }
  27624. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27625. //They intersected, and now they don't.
  27626. //is this trigger an exit trigger? execute an event.
  27627. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27628. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27629. }
  27630. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27631. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27632. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27633. return otherMesh === parameterMesh;
  27634. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27635. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27636. }
  27637. }
  27638. }
  27639. }
  27640. }
  27641. };
  27642. /**
  27643. * Render the scene
  27644. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27645. */
  27646. Scene.prototype.render = function (updateCameras) {
  27647. if (updateCameras === void 0) { updateCameras = true; }
  27648. if (this.isDisposed) {
  27649. return;
  27650. }
  27651. // Register components that have been associated lately to the scene.
  27652. this._registerTransientComponents();
  27653. this._activeParticles.fetchNewFrame();
  27654. this._totalVertices.fetchNewFrame();
  27655. this._activeIndices.fetchNewFrame();
  27656. this._activeBones.fetchNewFrame();
  27657. this._meshesForIntersections.reset();
  27658. this.resetCachedMaterial();
  27659. this.onBeforeAnimationsObservable.notifyObservers(this);
  27660. // Actions
  27661. if (this.actionManager) {
  27662. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27663. }
  27664. if (this._engine.isDeterministicLockStep()) {
  27665. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27666. var defaultFPS = (60.0 / 1000.0);
  27667. var defaultFrameTime = 1000 / 60; // frame time in MS
  27668. if (this._physicsEngine) {
  27669. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27670. }
  27671. var stepsTaken = 0;
  27672. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27673. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27674. internalSteps = Math.min(internalSteps, maxSubSteps);
  27675. do {
  27676. this.onBeforeStepObservable.notifyObservers(this);
  27677. // Animations
  27678. this._animationRatio = defaultFrameTime * defaultFPS;
  27679. this._animate();
  27680. this.onAfterAnimationsObservable.notifyObservers(this);
  27681. // Physics
  27682. if (this._physicsEngine) {
  27683. this.onBeforePhysicsObservable.notifyObservers(this);
  27684. this._physicsEngine._step(defaultFrameTime / 1000);
  27685. this.onAfterPhysicsObservable.notifyObservers(this);
  27686. }
  27687. this.onAfterStepObservable.notifyObservers(this);
  27688. this._currentStepId++;
  27689. stepsTaken++;
  27690. deltaTime -= defaultFrameTime;
  27691. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27692. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27693. }
  27694. else {
  27695. // Animations
  27696. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27697. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27698. this._animate();
  27699. this.onAfterAnimationsObservable.notifyObservers(this);
  27700. // Physics
  27701. if (this._physicsEngine) {
  27702. this.onBeforePhysicsObservable.notifyObservers(this);
  27703. this._physicsEngine._step(deltaTime / 1000.0);
  27704. this.onAfterPhysicsObservable.notifyObservers(this);
  27705. }
  27706. }
  27707. // Before camera update steps
  27708. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27709. var step = _a[_i];
  27710. step.action();
  27711. }
  27712. // Update Cameras
  27713. if (updateCameras) {
  27714. if (this.activeCameras.length > 0) {
  27715. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27716. var camera = this.activeCameras[cameraIndex];
  27717. camera.update();
  27718. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27719. // rig cameras
  27720. for (var index = 0; index < camera._rigCameras.length; index++) {
  27721. camera._rigCameras[index].update();
  27722. }
  27723. }
  27724. }
  27725. }
  27726. else if (this.activeCamera) {
  27727. this.activeCamera.update();
  27728. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27729. // rig cameras
  27730. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27731. this.activeCamera._rigCameras[index].update();
  27732. }
  27733. }
  27734. }
  27735. }
  27736. // Before render
  27737. this.onBeforeRenderObservable.notifyObservers(this);
  27738. // Customs render targets
  27739. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27740. var engine = this.getEngine();
  27741. var currentActiveCamera = this.activeCamera;
  27742. if (this.renderTargetsEnabled) {
  27743. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27744. this._intermediateRendering = true;
  27745. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27746. var renderTarget = this.customRenderTargets[customIndex];
  27747. if (renderTarget._shouldRender()) {
  27748. this._renderId++;
  27749. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27750. if (!this.activeCamera)
  27751. throw new Error("Active camera not set");
  27752. // Viewport
  27753. engine.setViewport(this.activeCamera.viewport);
  27754. // Camera
  27755. this.updateTransformMatrix();
  27756. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27757. }
  27758. }
  27759. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27760. this._intermediateRendering = false;
  27761. this._renderId++;
  27762. }
  27763. // Restore back buffer
  27764. if (this.customRenderTargets.length > 0) {
  27765. engine.restoreDefaultFramebuffer();
  27766. }
  27767. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27768. this.activeCamera = currentActiveCamera;
  27769. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27770. var step = _c[_b];
  27771. step.action();
  27772. }
  27773. // Clear
  27774. if (this.autoClearDepthAndStencil || this.autoClear) {
  27775. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27776. }
  27777. // Collects render targets from external components.
  27778. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27779. var step = _e[_d];
  27780. step.action(this._renderTargets);
  27781. }
  27782. // Multi-cameras?
  27783. if (this.activeCameras.length > 0) {
  27784. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27785. if (cameraIndex > 0) {
  27786. this._engine.clear(null, false, true, true);
  27787. }
  27788. this._processSubCameras(this.activeCameras[cameraIndex]);
  27789. }
  27790. }
  27791. else {
  27792. if (!this.activeCamera) {
  27793. throw new Error("No camera defined");
  27794. }
  27795. this._processSubCameras(this.activeCamera);
  27796. }
  27797. // Intersection checks
  27798. this._checkIntersections();
  27799. // Update the audio listener attached to the camera
  27800. if (BABYLON.AudioEngine) {
  27801. this._updateAudioParameters();
  27802. }
  27803. // After render
  27804. if (this.afterRender) {
  27805. this.afterRender();
  27806. }
  27807. this.onAfterRenderObservable.notifyObservers(this);
  27808. // Cleaning
  27809. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27810. var data = this._toBeDisposed.data[index];
  27811. if (data) {
  27812. data.dispose();
  27813. }
  27814. this._toBeDisposed[index] = null;
  27815. }
  27816. this._toBeDisposed.reset();
  27817. if (this.dumpNextRenderTargets) {
  27818. this.dumpNextRenderTargets = false;
  27819. }
  27820. this._activeBones.addCount(0, true);
  27821. this._activeIndices.addCount(0, true);
  27822. this._activeParticles.addCount(0, true);
  27823. };
  27824. Scene.prototype._updateAudioParameters = function () {
  27825. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27826. return;
  27827. }
  27828. var listeningCamera;
  27829. var audioEngine = BABYLON.Engine.audioEngine;
  27830. if (this.activeCameras.length > 0) {
  27831. listeningCamera = this.activeCameras[0];
  27832. }
  27833. else {
  27834. listeningCamera = this.activeCamera;
  27835. }
  27836. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27837. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27838. // for VR cameras
  27839. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27840. listeningCamera = listeningCamera.rigCameras[0];
  27841. }
  27842. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27843. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27844. cameraDirection.normalize();
  27845. // To avoid some errors on GearVR
  27846. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27847. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27848. }
  27849. var i;
  27850. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27851. var sound = this.mainSoundTrack.soundCollection[i];
  27852. if (sound.useCustomAttenuation) {
  27853. sound.updateDistanceFromListener();
  27854. }
  27855. }
  27856. for (i = 0; i < this.soundTracks.length; i++) {
  27857. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27858. sound = this.soundTracks[i].soundCollection[j];
  27859. if (sound.useCustomAttenuation) {
  27860. sound.updateDistanceFromListener();
  27861. }
  27862. }
  27863. }
  27864. }
  27865. };
  27866. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27867. // Audio
  27868. /**
  27869. * Gets or sets if audio support is enabled
  27870. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27871. */
  27872. get: function () {
  27873. return this._audioEnabled;
  27874. },
  27875. set: function (value) {
  27876. this._audioEnabled = value;
  27877. if (BABYLON.AudioEngine) {
  27878. if (this._audioEnabled) {
  27879. this._enableAudio();
  27880. }
  27881. else {
  27882. this._disableAudio();
  27883. }
  27884. }
  27885. },
  27886. enumerable: true,
  27887. configurable: true
  27888. });
  27889. Scene.prototype._disableAudio = function () {
  27890. var i;
  27891. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27892. this.mainSoundTrack.soundCollection[i].pause();
  27893. }
  27894. for (i = 0; i < this.soundTracks.length; i++) {
  27895. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27896. this.soundTracks[i].soundCollection[j].pause();
  27897. }
  27898. }
  27899. };
  27900. Scene.prototype._enableAudio = function () {
  27901. var i;
  27902. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27903. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27904. this.mainSoundTrack.soundCollection[i].play();
  27905. }
  27906. }
  27907. for (i = 0; i < this.soundTracks.length; i++) {
  27908. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27909. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27910. this.soundTracks[i].soundCollection[j].play();
  27911. }
  27912. }
  27913. }
  27914. };
  27915. Object.defineProperty(Scene.prototype, "headphone", {
  27916. /**
  27917. * Gets or sets if audio will be output to headphones
  27918. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27919. */
  27920. get: function () {
  27921. return this._headphone;
  27922. },
  27923. set: function (value) {
  27924. this._headphone = value;
  27925. if (BABYLON.AudioEngine) {
  27926. if (this._headphone) {
  27927. this._switchAudioModeForHeadphones();
  27928. }
  27929. else {
  27930. this._switchAudioModeForNormalSpeakers();
  27931. }
  27932. }
  27933. },
  27934. enumerable: true,
  27935. configurable: true
  27936. });
  27937. Scene.prototype._switchAudioModeForHeadphones = function () {
  27938. this.mainSoundTrack.switchPanningModelToHRTF();
  27939. for (var i = 0; i < this.soundTracks.length; i++) {
  27940. this.soundTracks[i].switchPanningModelToHRTF();
  27941. }
  27942. };
  27943. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27944. this.mainSoundTrack.switchPanningModelToEqualPower();
  27945. for (var i = 0; i < this.soundTracks.length; i++) {
  27946. this.soundTracks[i].switchPanningModelToEqualPower();
  27947. }
  27948. };
  27949. /**
  27950. * Freeze all materials
  27951. * A frozen material will not be updatable but should be faster to render
  27952. */
  27953. Scene.prototype.freezeMaterials = function () {
  27954. for (var i = 0; i < this.materials.length; i++) {
  27955. this.materials[i].freeze();
  27956. }
  27957. };
  27958. /**
  27959. * Unfreeze all materials
  27960. * A frozen material will not be updatable but should be faster to render
  27961. */
  27962. Scene.prototype.unfreezeMaterials = function () {
  27963. for (var i = 0; i < this.materials.length; i++) {
  27964. this.materials[i].unfreeze();
  27965. }
  27966. };
  27967. /**
  27968. * Releases all held ressources
  27969. */
  27970. Scene.prototype.dispose = function () {
  27971. this.beforeRender = null;
  27972. this.afterRender = null;
  27973. this.skeletons = [];
  27974. this.morphTargetManagers = [];
  27975. this._transientComponents = [];
  27976. this._isReadyForMeshStage.clear();
  27977. this._beforeEvaluateActiveMeshStage.clear();
  27978. this._evaluateSubMeshStage.clear();
  27979. this._activeMeshStage.clear();
  27980. this._cameraDrawRenderTargetStage.clear();
  27981. this._beforeCameraDrawStage.clear();
  27982. this._beforeRenderingGroupDrawStage.clear();
  27983. this._beforeRenderingMeshStage.clear();
  27984. this._afterRenderingMeshStage.clear();
  27985. this._afterRenderingGroupDrawStage.clear();
  27986. this._afterCameraDrawStage.clear();
  27987. this._beforeCameraUpdateStage.clear();
  27988. this._beforeClearStage.clear();
  27989. this._gatherRenderTargetsStage.clear();
  27990. this._rebuildGeometryStage.clear();
  27991. this._pointerMoveStage.clear();
  27992. this._pointerDownStage.clear();
  27993. this._pointerUpStage.clear();
  27994. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27995. var component = _a[_i];
  27996. component.dispose();
  27997. }
  27998. this.importedMeshesFiles = new Array();
  27999. this.stopAllAnimations();
  28000. this.resetCachedMaterial();
  28001. // Smart arrays
  28002. if (this.activeCamera) {
  28003. this.activeCamera._activeMeshes.dispose();
  28004. this.activeCamera = null;
  28005. }
  28006. this._activeMeshes.dispose();
  28007. this._renderingManager.dispose();
  28008. this._processedMaterials.dispose();
  28009. this._activeParticleSystems.dispose();
  28010. this._activeSkeletons.dispose();
  28011. this._softwareSkinnedMeshes.dispose();
  28012. this._renderTargets.dispose();
  28013. this._registeredForLateAnimationBindings.dispose();
  28014. this._meshesForIntersections.dispose();
  28015. this._toBeDisposed.dispose();
  28016. // Abort active requests
  28017. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28018. var request = _c[_b];
  28019. request.abort();
  28020. }
  28021. // Debug layer
  28022. if (this._debugLayer) {
  28023. this._debugLayer.hide();
  28024. }
  28025. // Events
  28026. this.onDisposeObservable.notifyObservers(this);
  28027. this.onDisposeObservable.clear();
  28028. this.onBeforeRenderObservable.clear();
  28029. this.onAfterRenderObservable.clear();
  28030. this.onBeforeRenderTargetsRenderObservable.clear();
  28031. this.onAfterRenderTargetsRenderObservable.clear();
  28032. this.onAfterStepObservable.clear();
  28033. this.onBeforeStepObservable.clear();
  28034. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28035. this.onAfterActiveMeshesEvaluationObservable.clear();
  28036. this.onBeforeParticlesRenderingObservable.clear();
  28037. this.onAfterParticlesRenderingObservable.clear();
  28038. this.onBeforeDrawPhaseObservable.clear();
  28039. this.onAfterDrawPhaseObservable.clear();
  28040. this.onBeforePhysicsObservable.clear();
  28041. this.onAfterPhysicsObservable.clear();
  28042. this.onBeforeAnimationsObservable.clear();
  28043. this.onAfterAnimationsObservable.clear();
  28044. this.onDataLoadedObservable.clear();
  28045. this.onBeforeRenderingGroupObservable.clear();
  28046. this.onAfterRenderingGroupObservable.clear();
  28047. this.detachControl();
  28048. // Release sounds & sounds tracks
  28049. if (BABYLON.AudioEngine) {
  28050. this.disposeSounds();
  28051. }
  28052. // VR Helper
  28053. if (this.VRHelper) {
  28054. this.VRHelper.dispose();
  28055. }
  28056. // Detach cameras
  28057. var canvas = this._engine.getRenderingCanvas();
  28058. if (canvas) {
  28059. var index;
  28060. for (index = 0; index < this.cameras.length; index++) {
  28061. this.cameras[index].detachControl(canvas);
  28062. }
  28063. }
  28064. // Release animation groups
  28065. while (this.animationGroups.length) {
  28066. this.animationGroups[0].dispose();
  28067. }
  28068. // Release lights
  28069. while (this.lights.length) {
  28070. this.lights[0].dispose();
  28071. }
  28072. // Release meshes
  28073. while (this.meshes.length) {
  28074. this.meshes[0].dispose(true);
  28075. }
  28076. while (this.transformNodes.length) {
  28077. this.removeTransformNode(this.transformNodes[0]);
  28078. }
  28079. // Release cameras
  28080. while (this.cameras.length) {
  28081. this.cameras[0].dispose();
  28082. }
  28083. // Release materials
  28084. if (this.defaultMaterial) {
  28085. this.defaultMaterial.dispose();
  28086. }
  28087. while (this.multiMaterials.length) {
  28088. this.multiMaterials[0].dispose();
  28089. }
  28090. while (this.materials.length) {
  28091. this.materials[0].dispose();
  28092. }
  28093. // Release particles
  28094. while (this.particleSystems.length) {
  28095. this.particleSystems[0].dispose();
  28096. }
  28097. // Release postProcesses
  28098. while (this.postProcesses.length) {
  28099. this.postProcesses[0].dispose();
  28100. }
  28101. // Release textures
  28102. while (this.textures.length) {
  28103. this.textures[0].dispose();
  28104. }
  28105. // Release UBO
  28106. this._sceneUbo.dispose();
  28107. if (this._alternateSceneUbo) {
  28108. this._alternateSceneUbo.dispose();
  28109. }
  28110. // Post-processes
  28111. this.postProcessManager.dispose();
  28112. // Physics
  28113. if (this._physicsEngine) {
  28114. this.disablePhysicsEngine();
  28115. }
  28116. // Remove from engine
  28117. index = this._engine.scenes.indexOf(this);
  28118. if (index > -1) {
  28119. this._engine.scenes.splice(index, 1);
  28120. }
  28121. this._engine.wipeCaches(true);
  28122. this._isDisposed = true;
  28123. };
  28124. Object.defineProperty(Scene.prototype, "isDisposed", {
  28125. /**
  28126. * Gets if the scene is already disposed
  28127. */
  28128. get: function () {
  28129. return this._isDisposed;
  28130. },
  28131. enumerable: true,
  28132. configurable: true
  28133. });
  28134. /**
  28135. * Releases sounds & soundtracks
  28136. */
  28137. Scene.prototype.disposeSounds = function () {
  28138. if (!this._mainSoundTrack) {
  28139. return;
  28140. }
  28141. this.mainSoundTrack.dispose();
  28142. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28143. this.soundTracks[scIndex].dispose();
  28144. }
  28145. };
  28146. /**
  28147. * Call this function to reduce memory footprint of the scene.
  28148. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28149. */
  28150. Scene.prototype.clearCachedVertexData = function () {
  28151. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28152. var mesh = this.meshes[meshIndex];
  28153. var geometry = mesh.geometry;
  28154. if (geometry) {
  28155. geometry._indices = [];
  28156. for (var vbName in geometry._vertexBuffers) {
  28157. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28158. continue;
  28159. }
  28160. geometry._vertexBuffers[vbName]._buffer._data = null;
  28161. }
  28162. }
  28163. }
  28164. };
  28165. /**
  28166. * This function will remove the local cached buffer data from texture.
  28167. * It will save memory but will prevent the texture from being rebuilt
  28168. */
  28169. Scene.prototype.cleanCachedTextureBuffer = function () {
  28170. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28171. var baseTexture = _a[_i];
  28172. var buffer = baseTexture._buffer;
  28173. if (buffer) {
  28174. baseTexture._buffer = null;
  28175. }
  28176. }
  28177. };
  28178. // Octrees
  28179. /**
  28180. * Get the world extend vectors with an optional filter
  28181. *
  28182. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28183. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28184. */
  28185. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28186. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28187. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28188. filterPredicate = filterPredicate || (function () { return true; });
  28189. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28190. mesh.computeWorldMatrix(true);
  28191. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28192. return;
  28193. }
  28194. var boundingInfo = mesh.getBoundingInfo();
  28195. var minBox = boundingInfo.boundingBox.minimumWorld;
  28196. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28197. BABYLON.Tools.CheckExtends(minBox, min, max);
  28198. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28199. });
  28200. return {
  28201. min: min,
  28202. max: max
  28203. };
  28204. };
  28205. /**
  28206. * Creates or updates the octree used to boost selection (picking)
  28207. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28208. * @param maxCapacity defines the maximum capacity per leaf
  28209. * @param maxDepth defines the maximum depth of the octree
  28210. * @returns an octree of AbstractMesh
  28211. */
  28212. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28213. if (maxCapacity === void 0) { maxCapacity = 64; }
  28214. if (maxDepth === void 0) { maxDepth = 2; }
  28215. if (!this._selectionOctree) {
  28216. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28217. }
  28218. var worldExtends = this.getWorldExtends();
  28219. // Update octree
  28220. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28221. return this._selectionOctree;
  28222. };
  28223. // Picking
  28224. /**
  28225. * Creates a ray that can be used to pick in the scene
  28226. * @param x defines the x coordinate of the origin (on-screen)
  28227. * @param y defines the y coordinate of the origin (on-screen)
  28228. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28229. * @param camera defines the camera to use for the picking
  28230. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28231. * @returns a Ray
  28232. */
  28233. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28234. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28235. var result = BABYLON.Ray.Zero();
  28236. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28237. return result;
  28238. };
  28239. /**
  28240. * Creates a ray that can be used to pick in the scene
  28241. * @param x defines the x coordinate of the origin (on-screen)
  28242. * @param y defines the y coordinate of the origin (on-screen)
  28243. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28244. * @param result defines the ray where to store the picking ray
  28245. * @param camera defines the camera to use for the picking
  28246. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28247. * @returns the current scene
  28248. */
  28249. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28250. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28251. var engine = this._engine;
  28252. if (!camera) {
  28253. if (!this.activeCamera)
  28254. throw new Error("Active camera not set");
  28255. camera = this.activeCamera;
  28256. }
  28257. var cameraViewport = camera.viewport;
  28258. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28259. // Moving coordinates to local viewport world
  28260. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28261. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28262. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28263. return this;
  28264. };
  28265. /**
  28266. * Creates a ray that can be used to pick in the scene
  28267. * @param x defines the x coordinate of the origin (on-screen)
  28268. * @param y defines the y coordinate of the origin (on-screen)
  28269. * @param camera defines the camera to use for the picking
  28270. * @returns a Ray
  28271. */
  28272. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28273. var result = BABYLON.Ray.Zero();
  28274. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28275. return result;
  28276. };
  28277. /**
  28278. * Creates a ray that can be used to pick in the scene
  28279. * @param x defines the x coordinate of the origin (on-screen)
  28280. * @param y defines the y coordinate of the origin (on-screen)
  28281. * @param result defines the ray where to store the picking ray
  28282. * @param camera defines the camera to use for the picking
  28283. * @returns the current scene
  28284. */
  28285. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28286. if (!BABYLON.PickingInfo) {
  28287. return this;
  28288. }
  28289. var engine = this._engine;
  28290. if (!camera) {
  28291. if (!this.activeCamera)
  28292. throw new Error("Active camera not set");
  28293. camera = this.activeCamera;
  28294. }
  28295. var cameraViewport = camera.viewport;
  28296. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28297. var identity = BABYLON.Matrix.Identity();
  28298. // Moving coordinates to local viewport world
  28299. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28300. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28301. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28302. return this;
  28303. };
  28304. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28305. if (!BABYLON.PickingInfo) {
  28306. return null;
  28307. }
  28308. var pickingInfo = null;
  28309. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28310. var mesh = this.meshes[meshIndex];
  28311. if (predicate) {
  28312. if (!predicate(mesh)) {
  28313. continue;
  28314. }
  28315. }
  28316. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28317. continue;
  28318. }
  28319. var world = mesh.getWorldMatrix();
  28320. var ray = rayFunction(world);
  28321. var result = mesh.intersects(ray, fastCheck);
  28322. if (!result || !result.hit)
  28323. continue;
  28324. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28325. continue;
  28326. pickingInfo = result;
  28327. if (fastCheck) {
  28328. break;
  28329. }
  28330. }
  28331. return pickingInfo || new BABYLON.PickingInfo();
  28332. };
  28333. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28334. if (!BABYLON.PickingInfo) {
  28335. return null;
  28336. }
  28337. var pickingInfos = new Array();
  28338. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28339. var mesh = this.meshes[meshIndex];
  28340. if (predicate) {
  28341. if (!predicate(mesh)) {
  28342. continue;
  28343. }
  28344. }
  28345. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28346. continue;
  28347. }
  28348. var world = mesh.getWorldMatrix();
  28349. var ray = rayFunction(world);
  28350. var result = mesh.intersects(ray, false);
  28351. if (!result || !result.hit)
  28352. continue;
  28353. pickingInfos.push(result);
  28354. }
  28355. return pickingInfos;
  28356. };
  28357. /** Launch a ray to try to pick a mesh in the scene
  28358. * @param x position on screen
  28359. * @param y position on screen
  28360. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28361. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28362. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28363. * @returns a PickingInfo
  28364. */
  28365. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28366. var _this = this;
  28367. if (!BABYLON.PickingInfo) {
  28368. return null;
  28369. }
  28370. var result = this._internalPick(function (world) {
  28371. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28372. return _this._tempPickingRay;
  28373. }, predicate, fastCheck);
  28374. if (result) {
  28375. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28376. }
  28377. return result;
  28378. };
  28379. /** Use the given ray to pick a mesh in the scene
  28380. * @param ray The ray to use to pick meshes
  28381. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28382. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28383. * @returns a PickingInfo
  28384. */
  28385. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28386. var _this = this;
  28387. var result = this._internalPick(function (world) {
  28388. if (!_this._pickWithRayInverseMatrix) {
  28389. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28390. }
  28391. world.invertToRef(_this._pickWithRayInverseMatrix);
  28392. if (!_this._cachedRayForTransform) {
  28393. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28394. }
  28395. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28396. return _this._cachedRayForTransform;
  28397. }, predicate, fastCheck);
  28398. if (result) {
  28399. result.ray = ray;
  28400. }
  28401. return result;
  28402. };
  28403. /**
  28404. * Launch a ray to try to pick a mesh in the scene
  28405. * @param x X position on screen
  28406. * @param y Y position on screen
  28407. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28408. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28409. * @returns an array of PickingInfo
  28410. */
  28411. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28412. var _this = this;
  28413. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28414. };
  28415. /**
  28416. * Launch a ray to try to pick a mesh in the scene
  28417. * @param ray Ray to use
  28418. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28419. * @returns an array of PickingInfo
  28420. */
  28421. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28422. var _this = this;
  28423. return this._internalMultiPick(function (world) {
  28424. if (!_this._pickWithRayInverseMatrix) {
  28425. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28426. }
  28427. world.invertToRef(_this._pickWithRayInverseMatrix);
  28428. if (!_this._cachedRayForTransform) {
  28429. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28430. }
  28431. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28432. return _this._cachedRayForTransform;
  28433. }, predicate);
  28434. };
  28435. /**
  28436. * Force the value of meshUnderPointer
  28437. * @param mesh defines the mesh to use
  28438. */
  28439. Scene.prototype.setPointerOverMesh = function (mesh) {
  28440. if (this._pointerOverMesh === mesh) {
  28441. return;
  28442. }
  28443. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28444. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28445. }
  28446. this._pointerOverMesh = mesh;
  28447. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28448. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28449. }
  28450. };
  28451. /**
  28452. * Gets the mesh under the pointer
  28453. * @returns a Mesh or null if no mesh is under the pointer
  28454. */
  28455. Scene.prototype.getPointerOverMesh = function () {
  28456. return this._pointerOverMesh;
  28457. };
  28458. // Physics
  28459. /**
  28460. * Gets the current physics engine
  28461. * @returns a PhysicsEngine or null if none attached
  28462. */
  28463. Scene.prototype.getPhysicsEngine = function () {
  28464. return this._physicsEngine;
  28465. };
  28466. /**
  28467. * Enables physics to the current scene
  28468. * @param gravity defines the scene's gravity for the physics engine
  28469. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28470. * @return a boolean indicating if the physics engine was initialized
  28471. */
  28472. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28473. if (gravity === void 0) { gravity = null; }
  28474. if (this._physicsEngine) {
  28475. return true;
  28476. }
  28477. try {
  28478. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28479. return true;
  28480. }
  28481. catch (e) {
  28482. BABYLON.Tools.Error(e.message);
  28483. return false;
  28484. }
  28485. };
  28486. /**
  28487. * Disables and disposes the physics engine associated with the scene
  28488. */
  28489. Scene.prototype.disablePhysicsEngine = function () {
  28490. if (!this._physicsEngine) {
  28491. return;
  28492. }
  28493. this._physicsEngine.dispose();
  28494. this._physicsEngine = null;
  28495. };
  28496. /**
  28497. * Gets a boolean indicating if there is an active physics engine
  28498. * @returns a boolean indicating if there is an active physics engine
  28499. */
  28500. Scene.prototype.isPhysicsEnabled = function () {
  28501. return this._physicsEngine !== undefined;
  28502. };
  28503. /**
  28504. * Deletes a physics compound impostor
  28505. * @param compound defines the compound to delete
  28506. */
  28507. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28508. var mesh = compound.parts[0].mesh;
  28509. if (mesh.physicsImpostor) {
  28510. mesh.physicsImpostor.dispose( /*true*/);
  28511. mesh.physicsImpostor = null;
  28512. }
  28513. };
  28514. // Misc.
  28515. /** @hidden */
  28516. Scene.prototype._rebuildGeometries = function () {
  28517. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28518. var geometry = _a[_i];
  28519. geometry._rebuild();
  28520. }
  28521. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28522. var mesh = _c[_b];
  28523. mesh._rebuild();
  28524. }
  28525. if (this.postProcessManager) {
  28526. this.postProcessManager._rebuild();
  28527. }
  28528. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28529. var component = _e[_d];
  28530. component.rebuild();
  28531. }
  28532. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28533. var system = _g[_f];
  28534. system.rebuild();
  28535. }
  28536. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28537. var step = _j[_h];
  28538. step.action();
  28539. }
  28540. };
  28541. /** @hidden */
  28542. Scene.prototype._rebuildTextures = function () {
  28543. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28544. var texture = _a[_i];
  28545. texture._rebuild();
  28546. }
  28547. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28548. };
  28549. /**
  28550. * Creates a default light for the scene.
  28551. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28552. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28553. */
  28554. Scene.prototype.createDefaultLight = function (replace) {
  28555. if (replace === void 0) { replace = false; }
  28556. // Dispose existing light in replace mode.
  28557. if (replace) {
  28558. if (this.lights) {
  28559. for (var i = 0; i < this.lights.length; i++) {
  28560. this.lights[i].dispose();
  28561. }
  28562. }
  28563. }
  28564. // Light
  28565. if (this.lights.length === 0) {
  28566. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28567. }
  28568. };
  28569. /**
  28570. * Creates a default camera for the scene.
  28571. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28572. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28573. * @param replace has default false, when true replaces the active camera in the scene
  28574. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28575. */
  28576. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28577. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28578. if (replace === void 0) { replace = false; }
  28579. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28580. // Dispose existing camera in replace mode.
  28581. if (replace) {
  28582. if (this.activeCamera) {
  28583. this.activeCamera.dispose();
  28584. this.activeCamera = null;
  28585. }
  28586. }
  28587. // Camera
  28588. if (!this.activeCamera) {
  28589. var worldExtends = this.getWorldExtends();
  28590. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28591. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28592. var camera;
  28593. var radius = worldSize.length() * 1.5;
  28594. // empty scene scenario!
  28595. if (!isFinite(radius)) {
  28596. radius = 1;
  28597. worldCenter.copyFromFloats(0, 0, 0);
  28598. }
  28599. if (createArcRotateCamera) {
  28600. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28601. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28602. arcRotateCamera.wheelPrecision = 100 / radius;
  28603. camera = arcRotateCamera;
  28604. }
  28605. else {
  28606. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28607. freeCamera.setTarget(worldCenter);
  28608. camera = freeCamera;
  28609. }
  28610. camera.minZ = radius * 0.01;
  28611. camera.maxZ = radius * 1000;
  28612. camera.speed = radius * 0.2;
  28613. this.activeCamera = camera;
  28614. var canvas = this.getEngine().getRenderingCanvas();
  28615. if (attachCameraControls && canvas) {
  28616. camera.attachControl(canvas);
  28617. }
  28618. }
  28619. };
  28620. /**
  28621. * Creates a default camera and a default light.
  28622. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28623. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28624. * @param replace has the default false, when true replaces the active camera/light in the scene
  28625. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28626. */
  28627. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28628. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28629. if (replace === void 0) { replace = false; }
  28630. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28631. this.createDefaultLight(replace);
  28632. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28633. };
  28634. /**
  28635. * Creates a new sky box
  28636. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28637. * @param environmentTexture defines the texture to use as environment texture
  28638. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28639. * @param scale defines the overall scale of the skybox
  28640. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28641. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28642. * @returns a new mesh holding the sky box
  28643. */
  28644. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28645. if (pbr === void 0) { pbr = false; }
  28646. if (scale === void 0) { scale = 1000; }
  28647. if (blur === void 0) { blur = 0; }
  28648. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28649. if (!environmentTexture) {
  28650. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28651. return null;
  28652. }
  28653. if (setGlobalEnvTexture) {
  28654. if (environmentTexture) {
  28655. this.environmentTexture = environmentTexture;
  28656. }
  28657. }
  28658. // Skybox
  28659. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28660. if (pbr) {
  28661. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28662. hdrSkyboxMaterial.backFaceCulling = false;
  28663. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28664. if (hdrSkyboxMaterial.reflectionTexture) {
  28665. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28666. }
  28667. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28668. hdrSkyboxMaterial.disableLighting = true;
  28669. hdrSkyboxMaterial.twoSidedLighting = true;
  28670. hdrSkybox.infiniteDistance = true;
  28671. hdrSkybox.material = hdrSkyboxMaterial;
  28672. }
  28673. else {
  28674. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28675. skyboxMaterial.backFaceCulling = false;
  28676. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28677. if (skyboxMaterial.reflectionTexture) {
  28678. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28679. }
  28680. skyboxMaterial.disableLighting = true;
  28681. hdrSkybox.infiniteDistance = true;
  28682. hdrSkybox.material = skyboxMaterial;
  28683. }
  28684. return hdrSkybox;
  28685. };
  28686. /**
  28687. * Creates a new environment
  28688. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28689. * @param options defines the options you can use to configure the environment
  28690. * @returns the new EnvironmentHelper
  28691. */
  28692. Scene.prototype.createDefaultEnvironment = function (options) {
  28693. if (BABYLON.EnvironmentHelper) {
  28694. return new BABYLON.EnvironmentHelper(options, this);
  28695. }
  28696. return null;
  28697. };
  28698. /**
  28699. * Creates a new VREXperienceHelper
  28700. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28701. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28702. * @returns a new VREXperienceHelper
  28703. */
  28704. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28705. if (webVROptions === void 0) { webVROptions = {}; }
  28706. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28707. };
  28708. // Tags
  28709. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28710. if (tagsQuery === undefined) {
  28711. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28712. return list;
  28713. }
  28714. var listByTags = [];
  28715. forEach = forEach || (function (item) { return; });
  28716. for (var i in list) {
  28717. var item = list[i];
  28718. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28719. listByTags.push(item);
  28720. forEach(item);
  28721. }
  28722. }
  28723. return listByTags;
  28724. };
  28725. /**
  28726. * Get a list of meshes by tags
  28727. * @param tagsQuery defines the tags query to use
  28728. * @param forEach defines a predicate used to filter results
  28729. * @returns an array of Mesh
  28730. */
  28731. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28732. return this._getByTags(this.meshes, tagsQuery, forEach);
  28733. };
  28734. /**
  28735. * Get a list of cameras by tags
  28736. * @param tagsQuery defines the tags query to use
  28737. * @param forEach defines a predicate used to filter results
  28738. * @returns an array of Camera
  28739. */
  28740. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28741. return this._getByTags(this.cameras, tagsQuery, forEach);
  28742. };
  28743. /**
  28744. * Get a list of lights by tags
  28745. * @param tagsQuery defines the tags query to use
  28746. * @param forEach defines a predicate used to filter results
  28747. * @returns an array of Light
  28748. */
  28749. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28750. return this._getByTags(this.lights, tagsQuery, forEach);
  28751. };
  28752. /**
  28753. * Get a list of materials by tags
  28754. * @param tagsQuery defines the tags query to use
  28755. * @param forEach defines a predicate used to filter results
  28756. * @returns an array of Material
  28757. */
  28758. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28759. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28760. };
  28761. /**
  28762. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28763. * This allowed control for front to back rendering or reversly depending of the special needs.
  28764. *
  28765. * @param renderingGroupId The rendering group id corresponding to its index
  28766. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28767. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28768. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28769. */
  28770. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28771. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28772. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28773. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28774. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28775. };
  28776. /**
  28777. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28778. *
  28779. * @param renderingGroupId The rendering group id corresponding to its index
  28780. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28781. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28782. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28783. */
  28784. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28785. if (depth === void 0) { depth = true; }
  28786. if (stencil === void 0) { stencil = true; }
  28787. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28788. };
  28789. /**
  28790. * Gets the current auto clear configuration for one rendering group of the rendering
  28791. * manager.
  28792. * @param index the rendering group index to get the information for
  28793. * @returns The auto clear setup for the requested rendering group
  28794. */
  28795. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28796. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28797. };
  28798. /**
  28799. * Will flag all materials as dirty to trigger new shader compilation
  28800. * @param flag defines the flag used to specify which material part must be marked as dirty
  28801. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28802. */
  28803. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28804. if (this.blockMaterialDirtyMechanism) {
  28805. return;
  28806. }
  28807. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28808. var material = _a[_i];
  28809. if (predicate && !predicate(material)) {
  28810. continue;
  28811. }
  28812. material.markAsDirty(flag);
  28813. }
  28814. };
  28815. /** @hidden */
  28816. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28817. var _this = this;
  28818. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28819. this._activeRequests.push(request);
  28820. request.onCompleteObservable.add(function (request) {
  28821. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28822. });
  28823. return request;
  28824. };
  28825. /** @hidden */
  28826. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28827. var _this = this;
  28828. return new Promise(function (resolve, reject) {
  28829. _this._loadFile(url, function (data) {
  28830. resolve(data);
  28831. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28832. reject(exception);
  28833. });
  28834. });
  28835. };
  28836. // Statics
  28837. Scene._uniqueIdCounter = 0;
  28838. /** The fog is deactivated */
  28839. Scene.FOGMODE_NONE = 0;
  28840. /** The fog density is following an exponential function */
  28841. Scene.FOGMODE_EXP = 1;
  28842. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28843. Scene.FOGMODE_EXP2 = 2;
  28844. /** The fog density is following a linear function. */
  28845. Scene.FOGMODE_LINEAR = 3;
  28846. /**
  28847. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28848. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28849. */
  28850. Scene.MinDeltaTime = 1.0;
  28851. /**
  28852. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28853. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28854. */
  28855. Scene.MaxDeltaTime = 1000.0;
  28856. /** The distance in pixel that you have to move to prevent some events */
  28857. Scene.DragMovementThreshold = 10; // in pixels
  28858. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28859. Scene.LongPressDelay = 500; // in milliseconds
  28860. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28861. Scene.DoubleClickDelay = 300; // in milliseconds
  28862. /** If you need to check double click without raising a single click at first click, enable this flag */
  28863. Scene.ExclusiveDoubleClickMode = false;
  28864. return Scene;
  28865. }(BABYLON.AbstractScene));
  28866. BABYLON.Scene = Scene;
  28867. })(BABYLON || (BABYLON = {}));
  28868. //# sourceMappingURL=babylon.scene.js.map
  28869. var BABYLON;
  28870. (function (BABYLON) {
  28871. /**
  28872. * Set of assets to keep when moving a scene into an asset container.
  28873. */
  28874. var KeepAssets = /** @class */ (function (_super) {
  28875. __extends(KeepAssets, _super);
  28876. function KeepAssets() {
  28877. return _super !== null && _super.apply(this, arguments) || this;
  28878. }
  28879. return KeepAssets;
  28880. }(BABYLON.AbstractScene));
  28881. BABYLON.KeepAssets = KeepAssets;
  28882. /**
  28883. * Container with a set of assets that can be added or removed from a scene.
  28884. */
  28885. var AssetContainer = /** @class */ (function (_super) {
  28886. __extends(AssetContainer, _super);
  28887. /**
  28888. * Instantiates an AssetContainer.
  28889. * @param scene The scene the AssetContainer belongs to.
  28890. */
  28891. function AssetContainer(scene) {
  28892. var _this = _super.call(this) || this;
  28893. _this.scene = scene;
  28894. return _this;
  28895. }
  28896. /**
  28897. * Adds all the assets from the container to the scene.
  28898. */
  28899. AssetContainer.prototype.addAllToScene = function () {
  28900. var _this = this;
  28901. this.cameras.forEach(function (o) {
  28902. _this.scene.addCamera(o);
  28903. });
  28904. this.lights.forEach(function (o) {
  28905. _this.scene.addLight(o);
  28906. });
  28907. this.meshes.forEach(function (o) {
  28908. _this.scene.addMesh(o);
  28909. });
  28910. this.skeletons.forEach(function (o) {
  28911. _this.scene.addSkeleton(o);
  28912. });
  28913. this.animations.forEach(function (o) {
  28914. _this.scene.addAnimation(o);
  28915. });
  28916. this.animationGroups.forEach(function (o) {
  28917. _this.scene.addAnimationGroup(o);
  28918. });
  28919. this.multiMaterials.forEach(function (o) {
  28920. _this.scene.addMultiMaterial(o);
  28921. });
  28922. this.materials.forEach(function (o) {
  28923. _this.scene.addMaterial(o);
  28924. });
  28925. this.morphTargetManagers.forEach(function (o) {
  28926. _this.scene.addMorphTargetManager(o);
  28927. });
  28928. this.geometries.forEach(function (o) {
  28929. _this.scene.addGeometry(o);
  28930. });
  28931. this.transformNodes.forEach(function (o) {
  28932. _this.scene.addTransformNode(o);
  28933. });
  28934. this.actionManagers.forEach(function (o) {
  28935. _this.scene.addActionManager(o);
  28936. });
  28937. this.sounds.forEach(function (o) {
  28938. o.play();
  28939. o.autoplay = true;
  28940. _this.scene.mainSoundTrack.AddSound(o);
  28941. });
  28942. this.textures.forEach(function (o) {
  28943. _this.scene.addTexture(o);
  28944. });
  28945. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28946. var component = _a[_i];
  28947. component.addFromContainer(this.scene);
  28948. }
  28949. };
  28950. /**
  28951. * Removes all the assets in the container from the scene
  28952. */
  28953. AssetContainer.prototype.removeAllFromScene = function () {
  28954. var _this = this;
  28955. this.cameras.forEach(function (o) {
  28956. _this.scene.removeCamera(o);
  28957. });
  28958. this.lights.forEach(function (o) {
  28959. _this.scene.removeLight(o);
  28960. });
  28961. this.meshes.forEach(function (o) {
  28962. _this.scene.removeMesh(o);
  28963. });
  28964. this.skeletons.forEach(function (o) {
  28965. _this.scene.removeSkeleton(o);
  28966. });
  28967. this.animations.forEach(function (o) {
  28968. _this.scene.removeAnimation(o);
  28969. });
  28970. this.animationGroups.forEach(function (o) {
  28971. _this.scene.removeAnimationGroup(o);
  28972. });
  28973. this.multiMaterials.forEach(function (o) {
  28974. _this.scene.removeMultiMaterial(o);
  28975. });
  28976. this.materials.forEach(function (o) {
  28977. _this.scene.removeMaterial(o);
  28978. });
  28979. this.morphTargetManagers.forEach(function (o) {
  28980. _this.scene.removeMorphTargetManager(o);
  28981. });
  28982. this.geometries.forEach(function (o) {
  28983. _this.scene.removeGeometry(o);
  28984. });
  28985. this.transformNodes.forEach(function (o) {
  28986. _this.scene.removeTransformNode(o);
  28987. });
  28988. this.actionManagers.forEach(function (o) {
  28989. _this.scene.removeActionManager(o);
  28990. });
  28991. this.sounds.forEach(function (o) {
  28992. o.stop();
  28993. o.autoplay = false;
  28994. _this.scene.mainSoundTrack.RemoveSound(o);
  28995. });
  28996. this.textures.forEach(function (o) {
  28997. _this.scene.removeTexture(o);
  28998. });
  28999. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29000. var component = _a[_i];
  29001. component.removeFromContainer(this.scene);
  29002. }
  29003. };
  29004. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29005. if (!sourceAssets) {
  29006. return;
  29007. }
  29008. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29009. var asset = sourceAssets_1[_i];
  29010. var move = true;
  29011. if (keepAssets) {
  29012. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29013. var keepAsset = keepAssets_1[_a];
  29014. if (asset === keepAsset) {
  29015. move = false;
  29016. break;
  29017. }
  29018. }
  29019. }
  29020. if (move) {
  29021. targetAssets.push(asset);
  29022. }
  29023. }
  29024. };
  29025. /**
  29026. * Removes all the assets contained in the scene and adds them to the container.
  29027. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29028. */
  29029. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29030. if (keepAssets === undefined) {
  29031. keepAssets = new KeepAssets();
  29032. }
  29033. for (var key in this) {
  29034. if (this.hasOwnProperty(key)) {
  29035. this[key] = this[key] || [];
  29036. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29037. }
  29038. }
  29039. this.removeAllFromScene();
  29040. };
  29041. /**
  29042. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29043. * @returns the root mesh
  29044. */
  29045. AssetContainer.prototype.createRootMesh = function () {
  29046. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29047. this.meshes.forEach(function (m) {
  29048. if (!m.parent) {
  29049. rootMesh.addChild(m);
  29050. }
  29051. });
  29052. this.meshes.unshift(rootMesh);
  29053. return rootMesh;
  29054. };
  29055. return AssetContainer;
  29056. }(BABYLON.AbstractScene));
  29057. BABYLON.AssetContainer = AssetContainer;
  29058. })(BABYLON || (BABYLON = {}));
  29059. //# sourceMappingURL=babylon.assetContainer.js.map
  29060. var BABYLON;
  29061. (function (BABYLON) {
  29062. var Buffer = /** @class */ (function () {
  29063. /**
  29064. * Constructor
  29065. * @param engine the engine
  29066. * @param data the data to use for this buffer
  29067. * @param updatable whether the data is updatable
  29068. * @param stride the stride (optional)
  29069. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29070. * @param instanced whether the buffer is instanced (optional)
  29071. * @param useBytes set to true if the stride in in bytes (optional)
  29072. */
  29073. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29074. if (stride === void 0) { stride = 0; }
  29075. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29076. if (instanced === void 0) { instanced = false; }
  29077. if (useBytes === void 0) { useBytes = false; }
  29078. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29079. this._engine = engine.getScene().getEngine();
  29080. }
  29081. else {
  29082. this._engine = engine;
  29083. }
  29084. this._updatable = updatable;
  29085. this._instanced = instanced;
  29086. this._data = data;
  29087. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29088. if (!postponeInternalCreation) { // by default
  29089. this.create();
  29090. }
  29091. }
  29092. /**
  29093. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29094. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29095. * @param offset defines offset in the buffer (0 by default)
  29096. * @param size defines the size in floats of attributes (position is 3 for instance)
  29097. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29098. * @param instanced defines if the vertex buffer contains indexed data
  29099. * @param useBytes defines if the offset and stride are in bytes
  29100. * @returns the new vertex buffer
  29101. */
  29102. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29103. if (useBytes === void 0) { useBytes = false; }
  29104. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29105. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29106. // a lot of these parameters are ignored as they are overriden by the buffer
  29107. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29108. };
  29109. // Properties
  29110. Buffer.prototype.isUpdatable = function () {
  29111. return this._updatable;
  29112. };
  29113. Buffer.prototype.getData = function () {
  29114. return this._data;
  29115. };
  29116. Buffer.prototype.getBuffer = function () {
  29117. return this._buffer;
  29118. };
  29119. /**
  29120. * Gets the stride in float32 units (i.e. byte stride / 4).
  29121. * May not be an integer if the byte stride is not divisible by 4.
  29122. * DEPRECATED. Use byteStride instead.
  29123. * @returns the stride in float32 units
  29124. */
  29125. Buffer.prototype.getStrideSize = function () {
  29126. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29127. };
  29128. // Methods
  29129. Buffer.prototype.create = function (data) {
  29130. if (data === void 0) { data = null; }
  29131. if (!data && this._buffer) {
  29132. return; // nothing to do
  29133. }
  29134. data = data || this._data;
  29135. if (!data) {
  29136. return;
  29137. }
  29138. if (!this._buffer) { // create buffer
  29139. if (this._updatable) {
  29140. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29141. this._data = data;
  29142. }
  29143. else {
  29144. this._buffer = this._engine.createVertexBuffer(data);
  29145. }
  29146. }
  29147. else if (this._updatable) { // update buffer
  29148. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29149. this._data = data;
  29150. }
  29151. };
  29152. /** @hidden */
  29153. Buffer.prototype._rebuild = function () {
  29154. this._buffer = null;
  29155. this.create(this._data);
  29156. };
  29157. Buffer.prototype.update = function (data) {
  29158. this.create(data);
  29159. };
  29160. /**
  29161. * Updates the data directly.
  29162. * @param data the new data
  29163. * @param offset the new offset
  29164. * @param vertexCount the vertex count (optional)
  29165. * @param useBytes set to true if the offset is in bytes
  29166. */
  29167. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29168. if (useBytes === void 0) { useBytes = false; }
  29169. if (!this._buffer) {
  29170. return;
  29171. }
  29172. if (this._updatable) { // update buffer
  29173. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29174. this._data = null;
  29175. }
  29176. };
  29177. Buffer.prototype.dispose = function () {
  29178. if (!this._buffer) {
  29179. return;
  29180. }
  29181. if (this._engine._releaseBuffer(this._buffer)) {
  29182. this._buffer = null;
  29183. }
  29184. };
  29185. return Buffer;
  29186. }());
  29187. BABYLON.Buffer = Buffer;
  29188. })(BABYLON || (BABYLON = {}));
  29189. //# sourceMappingURL=babylon.buffer.js.map
  29190. var BABYLON;
  29191. (function (BABYLON) {
  29192. var VertexBuffer = /** @class */ (function () {
  29193. /**
  29194. * Constructor
  29195. * @param engine the engine
  29196. * @param data the data to use for this vertex buffer
  29197. * @param kind the vertex buffer kind
  29198. * @param updatable whether the data is updatable
  29199. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29200. * @param stride the stride (optional)
  29201. * @param instanced whether the buffer is instanced (optional)
  29202. * @param offset the offset of the data (optional)
  29203. * @param size the number of components (optional)
  29204. * @param type the type of the component (optional)
  29205. * @param normalized whether the data contains normalized data (optional)
  29206. * @param useBytes set to true if stride and offset are in bytes (optional)
  29207. */
  29208. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29209. if (normalized === void 0) { normalized = false; }
  29210. if (useBytes === void 0) { useBytes = false; }
  29211. if (data instanceof BABYLON.Buffer) {
  29212. this._buffer = data;
  29213. this._ownsBuffer = false;
  29214. }
  29215. else {
  29216. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29217. this._ownsBuffer = true;
  29218. }
  29219. this._kind = kind;
  29220. if (type == undefined) {
  29221. var data_1 = this.getData();
  29222. this.type = VertexBuffer.FLOAT;
  29223. if (data_1 instanceof Int8Array)
  29224. this.type = VertexBuffer.BYTE;
  29225. else if (data_1 instanceof Uint8Array)
  29226. this.type = VertexBuffer.UNSIGNED_BYTE;
  29227. else if (data_1 instanceof Int16Array)
  29228. this.type = VertexBuffer.SHORT;
  29229. else if (data_1 instanceof Uint16Array)
  29230. this.type = VertexBuffer.UNSIGNED_SHORT;
  29231. else if (data_1 instanceof Int32Array)
  29232. this.type = VertexBuffer.INT;
  29233. else if (data_1 instanceof Uint32Array)
  29234. this.type = VertexBuffer.UNSIGNED_INT;
  29235. }
  29236. else {
  29237. this.type = type;
  29238. }
  29239. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29240. if (useBytes) {
  29241. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29242. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29243. this.byteOffset = offset || 0;
  29244. }
  29245. else {
  29246. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29247. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29248. this.byteOffset = (offset || 0) * typeByteLength;
  29249. }
  29250. this.normalized = normalized;
  29251. this._instanced = instanced !== undefined ? instanced : false;
  29252. this._instanceDivisor = instanced ? 1 : 0;
  29253. }
  29254. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29255. /**
  29256. * Gets or sets the instance divisor when in instanced mode
  29257. */
  29258. get: function () {
  29259. return this._instanceDivisor;
  29260. },
  29261. set: function (value) {
  29262. this._instanceDivisor = value;
  29263. if (value == 0) {
  29264. this._instanced = false;
  29265. }
  29266. else {
  29267. this._instanced = true;
  29268. }
  29269. },
  29270. enumerable: true,
  29271. configurable: true
  29272. });
  29273. /** @hidden */
  29274. VertexBuffer.prototype._rebuild = function () {
  29275. if (!this._buffer) {
  29276. return;
  29277. }
  29278. this._buffer._rebuild();
  29279. };
  29280. /**
  29281. * Returns the kind of the VertexBuffer (string).
  29282. */
  29283. VertexBuffer.prototype.getKind = function () {
  29284. return this._kind;
  29285. };
  29286. // Properties
  29287. /**
  29288. * Boolean : is the VertexBuffer updatable ?
  29289. */
  29290. VertexBuffer.prototype.isUpdatable = function () {
  29291. return this._buffer.isUpdatable();
  29292. };
  29293. /**
  29294. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29295. */
  29296. VertexBuffer.prototype.getData = function () {
  29297. return this._buffer.getData();
  29298. };
  29299. /**
  29300. * Returns the WebGLBuffer associated to the VertexBuffer.
  29301. */
  29302. VertexBuffer.prototype.getBuffer = function () {
  29303. return this._buffer.getBuffer();
  29304. };
  29305. /**
  29306. * Returns the stride as a multiple of the type byte length.
  29307. * DEPRECATED. Use byteStride instead.
  29308. */
  29309. VertexBuffer.prototype.getStrideSize = function () {
  29310. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29311. };
  29312. /**
  29313. * Returns the offset as a multiple of the type byte length.
  29314. * DEPRECATED. Use byteOffset instead.
  29315. */
  29316. VertexBuffer.prototype.getOffset = function () {
  29317. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29318. };
  29319. /**
  29320. * Returns the number of components per vertex attribute (integer).
  29321. */
  29322. VertexBuffer.prototype.getSize = function () {
  29323. return this._size;
  29324. };
  29325. /**
  29326. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29327. */
  29328. VertexBuffer.prototype.getIsInstanced = function () {
  29329. return this._instanced;
  29330. };
  29331. /**
  29332. * Returns the instancing divisor, zero for non-instanced (integer).
  29333. */
  29334. VertexBuffer.prototype.getInstanceDivisor = function () {
  29335. return this._instanceDivisor;
  29336. };
  29337. // Methods
  29338. /**
  29339. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29340. * Returns the created WebGLBuffer.
  29341. */
  29342. VertexBuffer.prototype.create = function (data) {
  29343. return this._buffer.create(data);
  29344. };
  29345. /**
  29346. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29347. * This function will create a new buffer if the current one is not updatable
  29348. * Returns the updated WebGLBuffer.
  29349. */
  29350. VertexBuffer.prototype.update = function (data) {
  29351. return this._buffer.update(data);
  29352. };
  29353. /**
  29354. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29355. * Returns the directly updated WebGLBuffer.
  29356. * @param data the new data
  29357. * @param offset the new offset
  29358. * @param useBytes set to true if the offset is in bytes
  29359. */
  29360. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29361. if (useBytes === void 0) { useBytes = false; }
  29362. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29363. };
  29364. /**
  29365. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29366. */
  29367. VertexBuffer.prototype.dispose = function () {
  29368. if (this._ownsBuffer) {
  29369. this._buffer.dispose();
  29370. }
  29371. };
  29372. /**
  29373. * Enumerates each value of this vertex buffer as numbers.
  29374. * @param count the number of values to enumerate
  29375. * @param callback the callback function called for each value
  29376. */
  29377. VertexBuffer.prototype.forEach = function (count, callback) {
  29378. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29379. };
  29380. Object.defineProperty(VertexBuffer, "PositionKind", {
  29381. get: function () {
  29382. return VertexBuffer._PositionKind;
  29383. },
  29384. enumerable: true,
  29385. configurable: true
  29386. });
  29387. Object.defineProperty(VertexBuffer, "NormalKind", {
  29388. get: function () {
  29389. return VertexBuffer._NormalKind;
  29390. },
  29391. enumerable: true,
  29392. configurable: true
  29393. });
  29394. Object.defineProperty(VertexBuffer, "TangentKind", {
  29395. get: function () {
  29396. return VertexBuffer._TangentKind;
  29397. },
  29398. enumerable: true,
  29399. configurable: true
  29400. });
  29401. Object.defineProperty(VertexBuffer, "UVKind", {
  29402. get: function () {
  29403. return VertexBuffer._UVKind;
  29404. },
  29405. enumerable: true,
  29406. configurable: true
  29407. });
  29408. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29409. get: function () {
  29410. return VertexBuffer._UV2Kind;
  29411. },
  29412. enumerable: true,
  29413. configurable: true
  29414. });
  29415. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29416. get: function () {
  29417. return VertexBuffer._UV3Kind;
  29418. },
  29419. enumerable: true,
  29420. configurable: true
  29421. });
  29422. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29423. get: function () {
  29424. return VertexBuffer._UV4Kind;
  29425. },
  29426. enumerable: true,
  29427. configurable: true
  29428. });
  29429. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29430. get: function () {
  29431. return VertexBuffer._UV5Kind;
  29432. },
  29433. enumerable: true,
  29434. configurable: true
  29435. });
  29436. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29437. get: function () {
  29438. return VertexBuffer._UV6Kind;
  29439. },
  29440. enumerable: true,
  29441. configurable: true
  29442. });
  29443. Object.defineProperty(VertexBuffer, "ColorKind", {
  29444. get: function () {
  29445. return VertexBuffer._ColorKind;
  29446. },
  29447. enumerable: true,
  29448. configurable: true
  29449. });
  29450. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29451. get: function () {
  29452. return VertexBuffer._MatricesIndicesKind;
  29453. },
  29454. enumerable: true,
  29455. configurable: true
  29456. });
  29457. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29458. get: function () {
  29459. return VertexBuffer._MatricesWeightsKind;
  29460. },
  29461. enumerable: true,
  29462. configurable: true
  29463. });
  29464. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29465. get: function () {
  29466. return VertexBuffer._MatricesIndicesExtraKind;
  29467. },
  29468. enumerable: true,
  29469. configurable: true
  29470. });
  29471. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29472. get: function () {
  29473. return VertexBuffer._MatricesWeightsExtraKind;
  29474. },
  29475. enumerable: true,
  29476. configurable: true
  29477. });
  29478. /**
  29479. * Deduces the stride given a kind.
  29480. * @param kind The kind string to deduce
  29481. * @returns The deduced stride
  29482. */
  29483. VertexBuffer.DeduceStride = function (kind) {
  29484. switch (kind) {
  29485. case VertexBuffer.UVKind:
  29486. case VertexBuffer.UV2Kind:
  29487. case VertexBuffer.UV3Kind:
  29488. case VertexBuffer.UV4Kind:
  29489. case VertexBuffer.UV5Kind:
  29490. case VertexBuffer.UV6Kind:
  29491. return 2;
  29492. case VertexBuffer.NormalKind:
  29493. case VertexBuffer.PositionKind:
  29494. return 3;
  29495. case VertexBuffer.ColorKind:
  29496. case VertexBuffer.MatricesIndicesKind:
  29497. case VertexBuffer.MatricesIndicesExtraKind:
  29498. case VertexBuffer.MatricesWeightsKind:
  29499. case VertexBuffer.MatricesWeightsExtraKind:
  29500. case VertexBuffer.TangentKind:
  29501. return 4;
  29502. default:
  29503. throw new Error("Invalid kind '" + kind + "'");
  29504. }
  29505. };
  29506. /**
  29507. * Gets the byte length of the given type.
  29508. * @param type the type
  29509. * @returns the number of bytes
  29510. */
  29511. VertexBuffer.GetTypeByteLength = function (type) {
  29512. switch (type) {
  29513. case VertexBuffer.BYTE:
  29514. case VertexBuffer.UNSIGNED_BYTE:
  29515. return 1;
  29516. case VertexBuffer.SHORT:
  29517. case VertexBuffer.UNSIGNED_SHORT:
  29518. return 2;
  29519. case VertexBuffer.INT:
  29520. case VertexBuffer.FLOAT:
  29521. return 4;
  29522. default:
  29523. throw new Error("Invalid type '" + type + "'");
  29524. }
  29525. };
  29526. /**
  29527. * Enumerates each value of the given parameters as numbers.
  29528. * @param data the data to enumerate
  29529. * @param byteOffset the byte offset of the data
  29530. * @param byteStride the byte stride of the data
  29531. * @param componentCount the number of components per element
  29532. * @param componentType the type of the component
  29533. * @param count the total number of components
  29534. * @param normalized whether the data is normalized
  29535. * @param callback the callback function called for each value
  29536. */
  29537. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29538. if (data instanceof Array) {
  29539. var offset = byteOffset / 4;
  29540. var stride = byteStride / 4;
  29541. for (var index = 0; index < count; index += componentCount) {
  29542. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29543. callback(data[offset + componentIndex], index + componentIndex);
  29544. }
  29545. offset += stride;
  29546. }
  29547. }
  29548. else {
  29549. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29550. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29551. for (var index = 0; index < count; index += componentCount) {
  29552. var componentByteOffset = byteOffset;
  29553. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29554. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29555. callback(value, index + componentIndex);
  29556. componentByteOffset += componentByteLength;
  29557. }
  29558. byteOffset += byteStride;
  29559. }
  29560. }
  29561. };
  29562. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29563. switch (type) {
  29564. case VertexBuffer.BYTE: {
  29565. var value = dataView.getInt8(byteOffset);
  29566. if (normalized) {
  29567. value = Math.max(value / 127, -1);
  29568. }
  29569. return value;
  29570. }
  29571. case VertexBuffer.UNSIGNED_BYTE: {
  29572. var value = dataView.getUint8(byteOffset);
  29573. if (normalized) {
  29574. value = value / 255;
  29575. }
  29576. return value;
  29577. }
  29578. case VertexBuffer.SHORT: {
  29579. var value = dataView.getInt16(byteOffset, true);
  29580. if (normalized) {
  29581. value = Math.max(value / 16383, -1);
  29582. }
  29583. return value;
  29584. }
  29585. case VertexBuffer.UNSIGNED_SHORT: {
  29586. var value = dataView.getUint16(byteOffset, true);
  29587. if (normalized) {
  29588. value = value / 65535;
  29589. }
  29590. return value;
  29591. }
  29592. case VertexBuffer.FLOAT: {
  29593. return dataView.getFloat32(byteOffset, true);
  29594. }
  29595. default: {
  29596. throw new Error("Invalid component type " + type);
  29597. }
  29598. }
  29599. };
  29600. /**
  29601. * The byte type.
  29602. */
  29603. VertexBuffer.BYTE = 5120;
  29604. /**
  29605. * The unsigned byte type.
  29606. */
  29607. VertexBuffer.UNSIGNED_BYTE = 5121;
  29608. /**
  29609. * The short type.
  29610. */
  29611. VertexBuffer.SHORT = 5122;
  29612. /**
  29613. * The unsigned short type.
  29614. */
  29615. VertexBuffer.UNSIGNED_SHORT = 5123;
  29616. /**
  29617. * The integer type.
  29618. */
  29619. VertexBuffer.INT = 5124;
  29620. /**
  29621. * The unsigned integer type.
  29622. */
  29623. VertexBuffer.UNSIGNED_INT = 5125;
  29624. /**
  29625. * The float type.
  29626. */
  29627. VertexBuffer.FLOAT = 5126;
  29628. // Enums
  29629. VertexBuffer._PositionKind = "position";
  29630. VertexBuffer._NormalKind = "normal";
  29631. VertexBuffer._TangentKind = "tangent";
  29632. VertexBuffer._UVKind = "uv";
  29633. VertexBuffer._UV2Kind = "uv2";
  29634. VertexBuffer._UV3Kind = "uv3";
  29635. VertexBuffer._UV4Kind = "uv4";
  29636. VertexBuffer._UV5Kind = "uv5";
  29637. VertexBuffer._UV6Kind = "uv6";
  29638. VertexBuffer._ColorKind = "color";
  29639. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29640. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29641. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29642. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29643. return VertexBuffer;
  29644. }());
  29645. BABYLON.VertexBuffer = VertexBuffer;
  29646. })(BABYLON || (BABYLON = {}));
  29647. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29648. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29649. var BABYLON;
  29650. (function (BABYLON) {
  29651. /**
  29652. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29653. */
  29654. var DummyInternalTextureTracker = /** @class */ (function () {
  29655. function DummyInternalTextureTracker() {
  29656. /**
  29657. * Gets or set the previous tracker in the list
  29658. */
  29659. this.previous = null;
  29660. /**
  29661. * Gets or set the next tracker in the list
  29662. */
  29663. this.next = null;
  29664. }
  29665. return DummyInternalTextureTracker;
  29666. }());
  29667. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29668. })(BABYLON || (BABYLON = {}));
  29669. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29670. var BABYLON;
  29671. (function (BABYLON) {
  29672. /**
  29673. * Class used to store data associated with WebGL texture data for the engine
  29674. * This class should not be used directly
  29675. */
  29676. var InternalTexture = /** @class */ (function () {
  29677. /**
  29678. * Creates a new InternalTexture
  29679. * @param engine defines the engine to use
  29680. * @param dataSource defines the type of data that will be used
  29681. */
  29682. function InternalTexture(engine, dataSource) {
  29683. /**
  29684. * Observable called when the texture is loaded
  29685. */
  29686. this.onLoadedObservable = new BABYLON.Observable();
  29687. /**
  29688. * Gets or set the previous tracker in the list
  29689. */
  29690. this.previous = null;
  29691. /**
  29692. * Gets or set the next tracker in the list
  29693. */
  29694. this.next = null;
  29695. // Private
  29696. /** @hidden */
  29697. this._initialSlot = -1;
  29698. /** @hidden */
  29699. this._designatedSlot = -1;
  29700. /** @hidden */
  29701. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29702. /** @hidden */
  29703. this._comparisonFunction = 0;
  29704. /** @hidden */
  29705. this._sphericalPolynomial = null;
  29706. /** @hidden */
  29707. this._lodGenerationScale = 0;
  29708. /** @hidden */
  29709. this._lodGenerationOffset = 0;
  29710. /** @hidden */
  29711. this._isRGBD = false;
  29712. /** @hidden */
  29713. this._references = 1;
  29714. this._engine = engine;
  29715. this._dataSource = dataSource;
  29716. this._webGLTexture = engine._createTexture();
  29717. }
  29718. /**
  29719. * Gets the Engine the texture belongs to.
  29720. * @returns The babylon engine
  29721. */
  29722. InternalTexture.prototype.getEngine = function () {
  29723. return this._engine;
  29724. };
  29725. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29726. /**
  29727. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29728. */
  29729. get: function () {
  29730. return this._dataSource;
  29731. },
  29732. enumerable: true,
  29733. configurable: true
  29734. });
  29735. /**
  29736. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29737. */
  29738. InternalTexture.prototype.incrementReferences = function () {
  29739. this._references++;
  29740. };
  29741. /**
  29742. * Change the size of the texture (not the size of the content)
  29743. * @param width defines the new width
  29744. * @param height defines the new height
  29745. * @param depth defines the new depth (1 by default)
  29746. */
  29747. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29748. if (depth === void 0) { depth = 1; }
  29749. this.width = width;
  29750. this.height = height;
  29751. this.depth = depth;
  29752. this.baseWidth = width;
  29753. this.baseHeight = height;
  29754. this.baseDepth = depth;
  29755. this._size = width * height * depth;
  29756. };
  29757. /** @hidden */
  29758. InternalTexture.prototype._rebuild = function () {
  29759. var _this = this;
  29760. var proxy;
  29761. this.isReady = false;
  29762. this._cachedCoordinatesMode = null;
  29763. this._cachedWrapU = null;
  29764. this._cachedWrapV = null;
  29765. this._cachedAnisotropicFilteringLevel = null;
  29766. switch (this._dataSource) {
  29767. case InternalTexture.DATASOURCE_TEMP:
  29768. return;
  29769. case InternalTexture.DATASOURCE_URL:
  29770. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29771. _this.isReady = true;
  29772. }, null, this._buffer, undefined, this.format);
  29773. proxy._swapAndDie(this);
  29774. return;
  29775. case InternalTexture.DATASOURCE_RAW:
  29776. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29777. proxy._swapAndDie(this);
  29778. this.isReady = true;
  29779. return;
  29780. case InternalTexture.DATASOURCE_RAW3D:
  29781. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29782. proxy._swapAndDie(this);
  29783. this.isReady = true;
  29784. return;
  29785. case InternalTexture.DATASOURCE_DYNAMIC:
  29786. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29787. proxy._swapAndDie(this);
  29788. // The engine will make sure to update content so no need to flag it as isReady = true
  29789. return;
  29790. case InternalTexture.DATASOURCE_RENDERTARGET:
  29791. var options = new BABYLON.RenderTargetCreationOptions();
  29792. options.generateDepthBuffer = this._generateDepthBuffer;
  29793. options.generateMipMaps = this.generateMipMaps;
  29794. options.generateStencilBuffer = this._generateStencilBuffer;
  29795. options.samplingMode = this.samplingMode;
  29796. options.type = this.type;
  29797. if (this.isCube) {
  29798. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29799. }
  29800. else {
  29801. var size = {
  29802. width: this.width,
  29803. height: this.height
  29804. };
  29805. proxy = this._engine.createRenderTargetTexture(size, options);
  29806. }
  29807. proxy._swapAndDie(this);
  29808. this.isReady = true;
  29809. return;
  29810. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29811. var depthTextureOptions = {
  29812. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29813. comparisonFunction: this._comparisonFunction,
  29814. generateStencil: this._generateStencilBuffer,
  29815. isCube: this.isCube
  29816. };
  29817. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29818. proxy._swapAndDie(this);
  29819. this.isReady = true;
  29820. return;
  29821. case InternalTexture.DATASOURCE_CUBE:
  29822. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29823. _this.isReady = true;
  29824. }, null, this.format, this._extension);
  29825. proxy._swapAndDie(this);
  29826. return;
  29827. case InternalTexture.DATASOURCE_CUBERAW:
  29828. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29829. proxy._swapAndDie(this);
  29830. this.isReady = true;
  29831. return;
  29832. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29833. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29834. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29835. _this.isReady = true;
  29836. });
  29837. proxy._swapAndDie(this);
  29838. return;
  29839. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29840. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29841. if (proxy) {
  29842. proxy._swapAndDie(_this);
  29843. }
  29844. _this.isReady = true;
  29845. }, null, this.format, this._extension);
  29846. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29847. return;
  29848. }
  29849. };
  29850. /** @hidden */
  29851. InternalTexture.prototype._swapAndDie = function (target) {
  29852. target._webGLTexture = this._webGLTexture;
  29853. if (this._framebuffer) {
  29854. target._framebuffer = this._framebuffer;
  29855. }
  29856. if (this._depthStencilBuffer) {
  29857. target._depthStencilBuffer = this._depthStencilBuffer;
  29858. }
  29859. if (this._lodTextureHigh) {
  29860. if (target._lodTextureHigh) {
  29861. target._lodTextureHigh.dispose();
  29862. }
  29863. target._lodTextureHigh = this._lodTextureHigh;
  29864. }
  29865. if (this._lodTextureMid) {
  29866. if (target._lodTextureMid) {
  29867. target._lodTextureMid.dispose();
  29868. }
  29869. target._lodTextureMid = this._lodTextureMid;
  29870. }
  29871. if (this._lodTextureLow) {
  29872. if (target._lodTextureLow) {
  29873. target._lodTextureLow.dispose();
  29874. }
  29875. target._lodTextureLow = this._lodTextureLow;
  29876. }
  29877. var cache = this._engine.getLoadedTexturesCache();
  29878. var index = cache.indexOf(this);
  29879. if (index !== -1) {
  29880. cache.splice(index, 1);
  29881. }
  29882. };
  29883. /**
  29884. * Dispose the current allocated resources
  29885. */
  29886. InternalTexture.prototype.dispose = function () {
  29887. if (!this._webGLTexture) {
  29888. return;
  29889. }
  29890. this._references--;
  29891. if (this._references === 0) {
  29892. this._engine._releaseTexture(this);
  29893. this._webGLTexture = null;
  29894. this.previous = null;
  29895. this.next = null;
  29896. }
  29897. };
  29898. /**
  29899. * The source of the texture data is unknown
  29900. */
  29901. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29902. /**
  29903. * Texture data comes from an URL
  29904. */
  29905. InternalTexture.DATASOURCE_URL = 1;
  29906. /**
  29907. * Texture data is only used for temporary storage
  29908. */
  29909. InternalTexture.DATASOURCE_TEMP = 2;
  29910. /**
  29911. * Texture data comes from raw data (ArrayBuffer)
  29912. */
  29913. InternalTexture.DATASOURCE_RAW = 3;
  29914. /**
  29915. * Texture content is dynamic (video or dynamic texture)
  29916. */
  29917. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29918. /**
  29919. * Texture content is generated by rendering to it
  29920. */
  29921. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29922. /**
  29923. * Texture content is part of a multi render target process
  29924. */
  29925. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29926. /**
  29927. * Texture data comes from a cube data file
  29928. */
  29929. InternalTexture.DATASOURCE_CUBE = 7;
  29930. /**
  29931. * Texture data comes from a raw cube data
  29932. */
  29933. InternalTexture.DATASOURCE_CUBERAW = 8;
  29934. /**
  29935. * Texture data come from a prefiltered cube data file
  29936. */
  29937. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29938. /**
  29939. * Texture content is raw 3D data
  29940. */
  29941. InternalTexture.DATASOURCE_RAW3D = 10;
  29942. /**
  29943. * Texture content is a depth texture
  29944. */
  29945. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29946. /**
  29947. * Texture data comes from a raw cube data encoded with RGBD
  29948. */
  29949. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29950. return InternalTexture;
  29951. }());
  29952. BABYLON.InternalTexture = InternalTexture;
  29953. })(BABYLON || (BABYLON = {}));
  29954. //# sourceMappingURL=babylon.internalTexture.js.map
  29955. var BABYLON;
  29956. (function (BABYLON) {
  29957. var BaseTexture = /** @class */ (function () {
  29958. function BaseTexture(scene) {
  29959. this._hasAlpha = false;
  29960. this.getAlphaFromRGB = false;
  29961. this.level = 1;
  29962. this.coordinatesIndex = 0;
  29963. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29964. /**
  29965. * | Value | Type | Description |
  29966. * | ----- | ------------------ | ----------- |
  29967. * | 0 | CLAMP_ADDRESSMODE | |
  29968. * | 1 | WRAP_ADDRESSMODE | |
  29969. * | 2 | MIRROR_ADDRESSMODE | |
  29970. */
  29971. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29972. /**
  29973. * | Value | Type | Description |
  29974. * | ----- | ------------------ | ----------- |
  29975. * | 0 | CLAMP_ADDRESSMODE | |
  29976. * | 1 | WRAP_ADDRESSMODE | |
  29977. * | 2 | MIRROR_ADDRESSMODE | |
  29978. */
  29979. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29980. /**
  29981. * | Value | Type | Description |
  29982. * | ----- | ------------------ | ----------- |
  29983. * | 0 | CLAMP_ADDRESSMODE | |
  29984. * | 1 | WRAP_ADDRESSMODE | |
  29985. * | 2 | MIRROR_ADDRESSMODE | |
  29986. */
  29987. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29988. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29989. this.isCube = false;
  29990. this.is3D = false;
  29991. this.gammaSpace = true;
  29992. this.invertZ = false;
  29993. this.lodLevelInAlpha = false;
  29994. this.isRenderTarget = false;
  29995. this.animations = new Array();
  29996. /**
  29997. * An event triggered when the texture is disposed.
  29998. */
  29999. this.onDisposeObservable = new BABYLON.Observable();
  30000. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30001. this._cachedSize = BABYLON.Size.Zero();
  30002. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30003. if (this._scene) {
  30004. this._scene.textures.push(this);
  30005. }
  30006. this._uid = null;
  30007. }
  30008. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30009. get: function () {
  30010. return this._hasAlpha;
  30011. },
  30012. set: function (value) {
  30013. if (this._hasAlpha === value) {
  30014. return;
  30015. }
  30016. this._hasAlpha = value;
  30017. if (this._scene) {
  30018. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30019. }
  30020. },
  30021. enumerable: true,
  30022. configurable: true
  30023. });
  30024. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30025. get: function () {
  30026. return this._coordinatesMode;
  30027. },
  30028. /**
  30029. * How a texture is mapped.
  30030. *
  30031. * | Value | Type | Description |
  30032. * | ----- | ----------------------------------- | ----------- |
  30033. * | 0 | EXPLICIT_MODE | |
  30034. * | 1 | SPHERICAL_MODE | |
  30035. * | 2 | PLANAR_MODE | |
  30036. * | 3 | CUBIC_MODE | |
  30037. * | 4 | PROJECTION_MODE | |
  30038. * | 5 | SKYBOX_MODE | |
  30039. * | 6 | INVCUBIC_MODE | |
  30040. * | 7 | EQUIRECTANGULAR_MODE | |
  30041. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30042. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30043. */
  30044. set: function (value) {
  30045. if (this._coordinatesMode === value) {
  30046. return;
  30047. }
  30048. this._coordinatesMode = value;
  30049. if (this._scene) {
  30050. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30051. }
  30052. },
  30053. enumerable: true,
  30054. configurable: true
  30055. });
  30056. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30057. /**
  30058. * Gets whether or not the texture contains RGBD data.
  30059. */
  30060. get: function () {
  30061. return this._texture != null && this._texture._isRGBD;
  30062. },
  30063. enumerable: true,
  30064. configurable: true
  30065. });
  30066. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30067. get: function () {
  30068. if (this._texture)
  30069. return this._texture._lodGenerationOffset;
  30070. return 0.0;
  30071. },
  30072. set: function (value) {
  30073. if (this._texture)
  30074. this._texture._lodGenerationOffset = value;
  30075. },
  30076. enumerable: true,
  30077. configurable: true
  30078. });
  30079. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30080. get: function () {
  30081. if (this._texture)
  30082. return this._texture._lodGenerationScale;
  30083. return 0.0;
  30084. },
  30085. set: function (value) {
  30086. if (this._texture)
  30087. this._texture._lodGenerationScale = value;
  30088. },
  30089. enumerable: true,
  30090. configurable: true
  30091. });
  30092. Object.defineProperty(BaseTexture.prototype, "uid", {
  30093. get: function () {
  30094. if (!this._uid) {
  30095. this._uid = BABYLON.Tools.RandomId();
  30096. }
  30097. return this._uid;
  30098. },
  30099. enumerable: true,
  30100. configurable: true
  30101. });
  30102. BaseTexture.prototype.toString = function () {
  30103. return this.name;
  30104. };
  30105. BaseTexture.prototype.getClassName = function () {
  30106. return "BaseTexture";
  30107. };
  30108. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30109. set: function (callback) {
  30110. if (this._onDisposeObserver) {
  30111. this.onDisposeObservable.remove(this._onDisposeObserver);
  30112. }
  30113. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30114. },
  30115. enumerable: true,
  30116. configurable: true
  30117. });
  30118. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30119. get: function () {
  30120. return true;
  30121. },
  30122. enumerable: true,
  30123. configurable: true
  30124. });
  30125. BaseTexture.prototype.getScene = function () {
  30126. return this._scene;
  30127. };
  30128. BaseTexture.prototype.getTextureMatrix = function () {
  30129. return BABYLON.Matrix.IdentityReadOnly;
  30130. };
  30131. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30132. return BABYLON.Matrix.IdentityReadOnly;
  30133. };
  30134. BaseTexture.prototype.getInternalTexture = function () {
  30135. return this._texture;
  30136. };
  30137. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30138. return !this.isBlocking || this.isReady();
  30139. };
  30140. BaseTexture.prototype.isReady = function () {
  30141. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30142. this.delayLoad();
  30143. return false;
  30144. }
  30145. if (this._texture) {
  30146. return this._texture.isReady;
  30147. }
  30148. return false;
  30149. };
  30150. BaseTexture.prototype.getSize = function () {
  30151. if (this._texture) {
  30152. if (this._texture.width) {
  30153. this._cachedSize.width = this._texture.width;
  30154. this._cachedSize.height = this._texture.height;
  30155. return this._cachedSize;
  30156. }
  30157. if (this._texture._size) {
  30158. this._cachedSize.width = this._texture._size;
  30159. this._cachedSize.height = this._texture._size;
  30160. return this._cachedSize;
  30161. }
  30162. }
  30163. return this._cachedSize;
  30164. };
  30165. BaseTexture.prototype.getBaseSize = function () {
  30166. if (!this.isReady() || !this._texture)
  30167. return BABYLON.Size.Zero();
  30168. if (this._texture._size) {
  30169. return new BABYLON.Size(this._texture._size, this._texture._size);
  30170. }
  30171. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30172. };
  30173. BaseTexture.prototype.scale = function (ratio) {
  30174. };
  30175. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30176. get: function () {
  30177. return false;
  30178. },
  30179. enumerable: true,
  30180. configurable: true
  30181. });
  30182. /** @hidden */
  30183. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30184. if (!this._scene) {
  30185. return null;
  30186. }
  30187. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30188. for (var index = 0; index < texturesCache.length; index++) {
  30189. var texturesCacheEntry = texturesCache[index];
  30190. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30191. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30192. texturesCacheEntry.incrementReferences();
  30193. return texturesCacheEntry;
  30194. }
  30195. }
  30196. }
  30197. return null;
  30198. };
  30199. /** @hidden */
  30200. BaseTexture.prototype._rebuild = function () {
  30201. };
  30202. BaseTexture.prototype.delayLoad = function () {
  30203. };
  30204. BaseTexture.prototype.clone = function () {
  30205. return null;
  30206. };
  30207. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30208. get: function () {
  30209. if (!this._texture) {
  30210. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30211. }
  30212. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30213. },
  30214. enumerable: true,
  30215. configurable: true
  30216. });
  30217. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30218. get: function () {
  30219. if (!this._texture) {
  30220. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30221. }
  30222. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30223. },
  30224. enumerable: true,
  30225. configurable: true
  30226. });
  30227. /**
  30228. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30229. * This will returns an RGBA array buffer containing either in values (0-255) or
  30230. * float values (0-1) depending of the underlying buffer type.
  30231. * @param faceIndex The face of the texture to read (in case of cube texture)
  30232. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30233. * @returns The Array buffer containing the pixels data.
  30234. */
  30235. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30236. if (faceIndex === void 0) { faceIndex = 0; }
  30237. if (level === void 0) { level = 0; }
  30238. if (!this._texture) {
  30239. return null;
  30240. }
  30241. var size = this.getSize();
  30242. var width = size.width;
  30243. var height = size.height;
  30244. var scene = this.getScene();
  30245. if (!scene) {
  30246. return null;
  30247. }
  30248. var engine = scene.getEngine();
  30249. if (level != 0) {
  30250. width = width / Math.pow(2, level);
  30251. height = height / Math.pow(2, level);
  30252. width = Math.round(width);
  30253. height = Math.round(height);
  30254. }
  30255. if (this._texture.isCube) {
  30256. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30257. }
  30258. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30259. };
  30260. BaseTexture.prototype.releaseInternalTexture = function () {
  30261. if (this._texture) {
  30262. this._texture.dispose();
  30263. this._texture = null;
  30264. }
  30265. };
  30266. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30267. get: function () {
  30268. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30269. return null;
  30270. }
  30271. if (!this._texture._sphericalPolynomial) {
  30272. this._texture._sphericalPolynomial =
  30273. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30274. }
  30275. return this._texture._sphericalPolynomial;
  30276. },
  30277. set: function (value) {
  30278. if (this._texture) {
  30279. this._texture._sphericalPolynomial = value;
  30280. }
  30281. },
  30282. enumerable: true,
  30283. configurable: true
  30284. });
  30285. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30286. get: function () {
  30287. if (this._texture) {
  30288. return this._texture._lodTextureHigh;
  30289. }
  30290. return null;
  30291. },
  30292. enumerable: true,
  30293. configurable: true
  30294. });
  30295. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30296. get: function () {
  30297. if (this._texture) {
  30298. return this._texture._lodTextureMid;
  30299. }
  30300. return null;
  30301. },
  30302. enumerable: true,
  30303. configurable: true
  30304. });
  30305. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30306. get: function () {
  30307. if (this._texture) {
  30308. return this._texture._lodTextureLow;
  30309. }
  30310. return null;
  30311. },
  30312. enumerable: true,
  30313. configurable: true
  30314. });
  30315. BaseTexture.prototype.dispose = function () {
  30316. if (!this._scene) {
  30317. return;
  30318. }
  30319. // Animations
  30320. this._scene.stopAnimation(this);
  30321. // Remove from scene
  30322. this._scene._removePendingData(this);
  30323. var index = this._scene.textures.indexOf(this);
  30324. if (index >= 0) {
  30325. this._scene.textures.splice(index, 1);
  30326. }
  30327. if (this._texture === undefined) {
  30328. return;
  30329. }
  30330. // Release
  30331. this.releaseInternalTexture();
  30332. // Callback
  30333. this.onDisposeObservable.notifyObservers(this);
  30334. this.onDisposeObservable.clear();
  30335. };
  30336. BaseTexture.prototype.serialize = function () {
  30337. if (!this.name) {
  30338. return null;
  30339. }
  30340. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30341. // Animations
  30342. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30343. return serializationObject;
  30344. };
  30345. BaseTexture.WhenAllReady = function (textures, callback) {
  30346. var numRemaining = textures.length;
  30347. if (numRemaining === 0) {
  30348. callback();
  30349. return;
  30350. }
  30351. var _loop_1 = function () {
  30352. texture = textures[i];
  30353. if (texture.isReady()) {
  30354. if (--numRemaining === 0) {
  30355. callback();
  30356. }
  30357. }
  30358. else {
  30359. onLoadObservable = texture.onLoadObservable;
  30360. var onLoadCallback_1 = function () {
  30361. onLoadObservable.removeCallback(onLoadCallback_1);
  30362. if (--numRemaining === 0) {
  30363. callback();
  30364. }
  30365. };
  30366. onLoadObservable.add(onLoadCallback_1);
  30367. }
  30368. };
  30369. var texture, onLoadObservable;
  30370. for (var i = 0; i < textures.length; i++) {
  30371. _loop_1();
  30372. }
  30373. };
  30374. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30375. __decorate([
  30376. BABYLON.serialize()
  30377. ], BaseTexture.prototype, "name", void 0);
  30378. __decorate([
  30379. BABYLON.serialize("hasAlpha")
  30380. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30381. __decorate([
  30382. BABYLON.serialize()
  30383. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30384. __decorate([
  30385. BABYLON.serialize()
  30386. ], BaseTexture.prototype, "level", void 0);
  30387. __decorate([
  30388. BABYLON.serialize()
  30389. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30390. __decorate([
  30391. BABYLON.serialize("coordinatesMode")
  30392. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30393. __decorate([
  30394. BABYLON.serialize()
  30395. ], BaseTexture.prototype, "wrapU", void 0);
  30396. __decorate([
  30397. BABYLON.serialize()
  30398. ], BaseTexture.prototype, "wrapV", void 0);
  30399. __decorate([
  30400. BABYLON.serialize()
  30401. ], BaseTexture.prototype, "wrapR", void 0);
  30402. __decorate([
  30403. BABYLON.serialize()
  30404. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30405. __decorate([
  30406. BABYLON.serialize()
  30407. ], BaseTexture.prototype, "isCube", void 0);
  30408. __decorate([
  30409. BABYLON.serialize()
  30410. ], BaseTexture.prototype, "is3D", void 0);
  30411. __decorate([
  30412. BABYLON.serialize()
  30413. ], BaseTexture.prototype, "gammaSpace", void 0);
  30414. __decorate([
  30415. BABYLON.serialize()
  30416. ], BaseTexture.prototype, "invertZ", void 0);
  30417. __decorate([
  30418. BABYLON.serialize()
  30419. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30420. __decorate([
  30421. BABYLON.serialize()
  30422. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30423. __decorate([
  30424. BABYLON.serialize()
  30425. ], BaseTexture.prototype, "lodGenerationScale", null);
  30426. __decorate([
  30427. BABYLON.serialize()
  30428. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30429. return BaseTexture;
  30430. }());
  30431. BABYLON.BaseTexture = BaseTexture;
  30432. })(BABYLON || (BABYLON = {}));
  30433. //# sourceMappingURL=babylon.baseTexture.js.map
  30434. var BABYLON;
  30435. (function (BABYLON) {
  30436. var Texture = /** @class */ (function (_super) {
  30437. __extends(Texture, _super);
  30438. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30439. if (noMipmap === void 0) { noMipmap = false; }
  30440. if (invertY === void 0) { invertY = true; }
  30441. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30442. if (onLoad === void 0) { onLoad = null; }
  30443. if (onError === void 0) { onError = null; }
  30444. if (buffer === void 0) { buffer = null; }
  30445. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30446. var _this = _super.call(this, scene) || this;
  30447. _this.uOffset = 0;
  30448. _this.vOffset = 0;
  30449. _this.uScale = 1.0;
  30450. _this.vScale = 1.0;
  30451. _this.uAng = 0;
  30452. _this.vAng = 0;
  30453. _this.wAng = 0;
  30454. /**
  30455. * Defines the center of rotation (U)
  30456. */
  30457. _this.uRotationCenter = 0.5;
  30458. /**
  30459. * Defines the center of rotation (V)
  30460. */
  30461. _this.vRotationCenter = 0.5;
  30462. /**
  30463. * Defines the center of rotation (W)
  30464. */
  30465. _this.wRotationCenter = 0.5;
  30466. _this._isBlocking = true;
  30467. _this.name = url || "";
  30468. _this.url = url;
  30469. _this._noMipmap = noMipmap;
  30470. _this._invertY = invertY;
  30471. _this._samplingMode = samplingMode;
  30472. _this._buffer = buffer;
  30473. _this._deleteBuffer = deleteBuffer;
  30474. if (format) {
  30475. _this._format = format;
  30476. }
  30477. scene = _this.getScene();
  30478. if (!scene) {
  30479. return _this;
  30480. }
  30481. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30482. var load = function () {
  30483. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30484. _this.onLoadObservable.notifyObservers(_this);
  30485. }
  30486. if (onLoad) {
  30487. onLoad();
  30488. }
  30489. if (!_this.isBlocking && scene) {
  30490. scene.resetCachedMaterial();
  30491. }
  30492. };
  30493. if (!_this.url) {
  30494. _this._delayedOnLoad = load;
  30495. _this._delayedOnError = onError;
  30496. return _this;
  30497. }
  30498. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30499. if (!_this._texture) {
  30500. if (!scene.useDelayedTextureLoading) {
  30501. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30502. if (deleteBuffer) {
  30503. delete _this._buffer;
  30504. }
  30505. }
  30506. else {
  30507. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30508. _this._delayedOnLoad = load;
  30509. _this._delayedOnError = onError;
  30510. }
  30511. }
  30512. else {
  30513. if (_this._texture.isReady) {
  30514. BABYLON.Tools.SetImmediate(function () { return load(); });
  30515. }
  30516. else {
  30517. _this._texture.onLoadedObservable.add(load);
  30518. }
  30519. }
  30520. return _this;
  30521. }
  30522. Object.defineProperty(Texture.prototype, "noMipmap", {
  30523. get: function () {
  30524. return this._noMipmap;
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. Object.defineProperty(Texture.prototype, "isBlocking", {
  30530. get: function () {
  30531. return this._isBlocking;
  30532. },
  30533. set: function (value) {
  30534. this._isBlocking = value;
  30535. },
  30536. enumerable: true,
  30537. configurable: true
  30538. });
  30539. Object.defineProperty(Texture.prototype, "samplingMode", {
  30540. get: function () {
  30541. return this._samplingMode;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. /**
  30547. * Update the url (and optional buffer) of this texture if url was null during construction.
  30548. * @param url the url of the texture
  30549. * @param buffer the buffer of the texture (defaults to null)
  30550. */
  30551. Texture.prototype.updateURL = function (url, buffer) {
  30552. if (buffer === void 0) { buffer = null; }
  30553. if (this.url) {
  30554. throw new Error("URL is already set");
  30555. }
  30556. this.url = url;
  30557. this._buffer = buffer;
  30558. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30559. this.delayLoad();
  30560. };
  30561. Texture.prototype.delayLoad = function () {
  30562. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30563. return;
  30564. }
  30565. var scene = this.getScene();
  30566. if (!scene) {
  30567. return;
  30568. }
  30569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30570. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30571. if (!this._texture) {
  30572. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30573. if (this._deleteBuffer) {
  30574. delete this._buffer;
  30575. }
  30576. }
  30577. else {
  30578. if (this._delayedOnLoad) {
  30579. if (this._texture.isReady) {
  30580. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30581. }
  30582. else {
  30583. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30584. }
  30585. }
  30586. }
  30587. this._delayedOnLoad = null;
  30588. this._delayedOnError = null;
  30589. };
  30590. /**
  30591. * Default is Trilinear mode.
  30592. *
  30593. * | Value | Type | Description |
  30594. * | ----- | ------------------ | ----------- |
  30595. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30596. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30597. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30598. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30599. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30600. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30601. * | 7 | NEAREST_LINEAR | |
  30602. * | 8 | NEAREST_NEAREST | |
  30603. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30604. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30605. * | 11 | LINEAR_LINEAR | |
  30606. * | 12 | LINEAR_NEAREST | |
  30607. *
  30608. * > _mag_: magnification filter (close to the viewer)
  30609. * > _min_: minification filter (far from the viewer)
  30610. * > _mip_: filter used between mip map levels
  30611. *
  30612. */
  30613. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30614. if (!this._texture) {
  30615. return;
  30616. }
  30617. var scene = this.getScene();
  30618. if (!scene) {
  30619. return;
  30620. }
  30621. this._samplingMode = samplingMode;
  30622. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30623. };
  30624. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30625. x *= this.uScale;
  30626. y *= this.vScale;
  30627. x -= this.uRotationCenter * this.uScale;
  30628. y -= this.vRotationCenter * this.vScale;
  30629. z -= this.wRotationCenter;
  30630. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30631. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30632. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30633. t.z += this.wRotationCenter;
  30634. };
  30635. Texture.prototype.getTextureMatrix = function () {
  30636. var _this = this;
  30637. if (this.uOffset === this._cachedUOffset &&
  30638. this.vOffset === this._cachedVOffset &&
  30639. this.uScale === this._cachedUScale &&
  30640. this.vScale === this._cachedVScale &&
  30641. this.uAng === this._cachedUAng &&
  30642. this.vAng === this._cachedVAng &&
  30643. this.wAng === this._cachedWAng) {
  30644. return this._cachedTextureMatrix;
  30645. }
  30646. this._cachedUOffset = this.uOffset;
  30647. this._cachedVOffset = this.vOffset;
  30648. this._cachedUScale = this.uScale;
  30649. this._cachedVScale = this.vScale;
  30650. this._cachedUAng = this.uAng;
  30651. this._cachedVAng = this.vAng;
  30652. this._cachedWAng = this.wAng;
  30653. if (!this._cachedTextureMatrix) {
  30654. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30655. this._rowGenerationMatrix = new BABYLON.Matrix();
  30656. this._t0 = BABYLON.Vector3.Zero();
  30657. this._t1 = BABYLON.Vector3.Zero();
  30658. this._t2 = BABYLON.Vector3.Zero();
  30659. }
  30660. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30661. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30662. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30663. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30664. this._t1.subtractInPlace(this._t0);
  30665. this._t2.subtractInPlace(this._t0);
  30666. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30667. this._cachedTextureMatrix.m[0] = this._t1.x;
  30668. this._cachedTextureMatrix.m[1] = this._t1.y;
  30669. this._cachedTextureMatrix.m[2] = this._t1.z;
  30670. this._cachedTextureMatrix.m[4] = this._t2.x;
  30671. this._cachedTextureMatrix.m[5] = this._t2.y;
  30672. this._cachedTextureMatrix.m[6] = this._t2.z;
  30673. this._cachedTextureMatrix.m[8] = this._t0.x;
  30674. this._cachedTextureMatrix.m[9] = this._t0.y;
  30675. this._cachedTextureMatrix.m[10] = this._t0.z;
  30676. var scene = this.getScene();
  30677. if (!scene) {
  30678. return this._cachedTextureMatrix;
  30679. }
  30680. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30681. return mat.hasTexture(_this);
  30682. });
  30683. return this._cachedTextureMatrix;
  30684. };
  30685. Texture.prototype.getReflectionTextureMatrix = function () {
  30686. var _this = this;
  30687. var scene = this.getScene();
  30688. if (!scene) {
  30689. return this._cachedTextureMatrix;
  30690. }
  30691. if (this.uOffset === this._cachedUOffset &&
  30692. this.vOffset === this._cachedVOffset &&
  30693. this.uScale === this._cachedUScale &&
  30694. this.vScale === this._cachedVScale &&
  30695. this.coordinatesMode === this._cachedCoordinatesMode) {
  30696. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30697. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30698. return this._cachedTextureMatrix;
  30699. }
  30700. }
  30701. else {
  30702. return this._cachedTextureMatrix;
  30703. }
  30704. }
  30705. if (!this._cachedTextureMatrix) {
  30706. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30707. }
  30708. if (!this._projectionModeMatrix) {
  30709. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30710. }
  30711. this._cachedUOffset = this.uOffset;
  30712. this._cachedVOffset = this.vOffset;
  30713. this._cachedUScale = this.uScale;
  30714. this._cachedVScale = this.vScale;
  30715. this._cachedCoordinatesMode = this.coordinatesMode;
  30716. switch (this.coordinatesMode) {
  30717. case Texture.PLANAR_MODE:
  30718. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30719. this._cachedTextureMatrix[0] = this.uScale;
  30720. this._cachedTextureMatrix[5] = this.vScale;
  30721. this._cachedTextureMatrix[12] = this.uOffset;
  30722. this._cachedTextureMatrix[13] = this.vOffset;
  30723. break;
  30724. case Texture.PROJECTION_MODE:
  30725. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30726. this._projectionModeMatrix.m[0] = 0.5;
  30727. this._projectionModeMatrix.m[5] = -0.5;
  30728. this._projectionModeMatrix.m[10] = 0.0;
  30729. this._projectionModeMatrix.m[12] = 0.5;
  30730. this._projectionModeMatrix.m[13] = 0.5;
  30731. this._projectionModeMatrix.m[14] = 1.0;
  30732. this._projectionModeMatrix.m[15] = 1.0;
  30733. var projectionMatrix = scene.getProjectionMatrix();
  30734. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30735. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30736. break;
  30737. default:
  30738. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30739. break;
  30740. }
  30741. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30742. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30743. });
  30744. return this._cachedTextureMatrix;
  30745. };
  30746. Texture.prototype.clone = function () {
  30747. var _this = this;
  30748. return BABYLON.SerializationHelper.Clone(function () {
  30749. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30750. }, this);
  30751. };
  30752. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30753. get: function () {
  30754. if (!this._onLoadObservable) {
  30755. this._onLoadObservable = new BABYLON.Observable();
  30756. }
  30757. return this._onLoadObservable;
  30758. },
  30759. enumerable: true,
  30760. configurable: true
  30761. });
  30762. Texture.prototype.serialize = function () {
  30763. var serializationObject = _super.prototype.serialize.call(this);
  30764. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30765. serializationObject.base64String = this._buffer;
  30766. serializationObject.name = serializationObject.name.replace("data:", "");
  30767. }
  30768. serializationObject.invertY = this._invertY;
  30769. serializationObject.samplingMode = this.samplingMode;
  30770. return serializationObject;
  30771. };
  30772. Texture.prototype.getClassName = function () {
  30773. return "Texture";
  30774. };
  30775. Texture.prototype.dispose = function () {
  30776. _super.prototype.dispose.call(this);
  30777. if (this._onLoadObservable) {
  30778. this._onLoadObservable.clear();
  30779. this._onLoadObservable = null;
  30780. }
  30781. this._delayedOnLoad = null;
  30782. this._delayedOnError = null;
  30783. };
  30784. // Statics
  30785. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30786. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30787. if (onLoad === void 0) { onLoad = null; }
  30788. if (onError === void 0) { onError = null; }
  30789. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30790. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30791. };
  30792. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30793. if (parsedTexture.customType) {
  30794. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30795. // Update Sampling Mode
  30796. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30797. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30798. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30799. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30800. }
  30801. }
  30802. return parsedCustomTexture;
  30803. }
  30804. if (parsedTexture.isCube) {
  30805. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30806. }
  30807. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30808. return null;
  30809. }
  30810. var texture = BABYLON.SerializationHelper.Parse(function () {
  30811. var generateMipMaps = true;
  30812. if (parsedTexture.noMipmap) {
  30813. generateMipMaps = false;
  30814. }
  30815. if (parsedTexture.mirrorPlane) {
  30816. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30817. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30818. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30819. return mirrorTexture;
  30820. }
  30821. else if (parsedTexture.isRenderTarget) {
  30822. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30823. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30824. return renderTargetTexture;
  30825. }
  30826. else {
  30827. var texture;
  30828. if (parsedTexture.base64String) {
  30829. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30830. }
  30831. else {
  30832. var url = rootUrl + parsedTexture.name;
  30833. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30834. url = parsedTexture.url;
  30835. }
  30836. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30837. }
  30838. return texture;
  30839. }
  30840. }, parsedTexture, scene);
  30841. // Update Sampling Mode
  30842. if (parsedTexture.samplingMode) {
  30843. var sampling = parsedTexture.samplingMode;
  30844. if (texture._samplingMode !== sampling) {
  30845. texture.updateSamplingMode(sampling);
  30846. }
  30847. }
  30848. // Animations
  30849. if (parsedTexture.animations) {
  30850. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30851. var parsedAnimation = parsedTexture.animations[animationIndex];
  30852. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30853. }
  30854. }
  30855. return texture;
  30856. };
  30857. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30858. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30859. if (noMipmap === void 0) { noMipmap = false; }
  30860. if (invertY === void 0) { invertY = true; }
  30861. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30862. if (onLoad === void 0) { onLoad = null; }
  30863. if (onError === void 0) { onError = null; }
  30864. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30865. if (name.substr(0, 5) !== "data:") {
  30866. name = "data:" + name;
  30867. }
  30868. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30869. };
  30870. // Constants
  30871. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30872. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30873. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30874. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30875. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30876. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30877. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30878. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30879. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30880. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30881. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30882. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30883. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30884. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30885. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30886. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30887. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30888. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30889. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30890. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30891. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30892. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30893. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30894. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30895. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30896. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30897. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30898. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30899. /**
  30900. * 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
  30901. */
  30902. Texture.UseSerializedUrlIfAny = false;
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], Texture.prototype, "url", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "uOffset", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], Texture.prototype, "vOffset", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], Texture.prototype, "uScale", void 0);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], Texture.prototype, "vScale", void 0);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], Texture.prototype, "uAng", void 0);
  30921. __decorate([
  30922. BABYLON.serialize()
  30923. ], Texture.prototype, "vAng", void 0);
  30924. __decorate([
  30925. BABYLON.serialize()
  30926. ], Texture.prototype, "wAng", void 0);
  30927. __decorate([
  30928. BABYLON.serialize()
  30929. ], Texture.prototype, "uRotationCenter", void 0);
  30930. __decorate([
  30931. BABYLON.serialize()
  30932. ], Texture.prototype, "vRotationCenter", void 0);
  30933. __decorate([
  30934. BABYLON.serialize()
  30935. ], Texture.prototype, "wRotationCenter", void 0);
  30936. __decorate([
  30937. BABYLON.serialize()
  30938. ], Texture.prototype, "isBlocking", null);
  30939. return Texture;
  30940. }(BABYLON.BaseTexture));
  30941. BABYLON.Texture = Texture;
  30942. })(BABYLON || (BABYLON = {}));
  30943. //# sourceMappingURL=babylon.texture.js.map
  30944. var BABYLON;
  30945. (function (BABYLON) {
  30946. /**
  30947. * @hidden
  30948. **/
  30949. var _InstancesBatch = /** @class */ (function () {
  30950. function _InstancesBatch() {
  30951. this.mustReturn = false;
  30952. this.visibleInstances = new Array();
  30953. this.renderSelf = new Array();
  30954. }
  30955. return _InstancesBatch;
  30956. }());
  30957. BABYLON._InstancesBatch = _InstancesBatch;
  30958. var Mesh = /** @class */ (function (_super) {
  30959. __extends(Mesh, _super);
  30960. /**
  30961. * @constructor
  30962. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30963. * @param {Scene} scene The scene to add this mesh to.
  30964. * @param {Node} parent The parent of this mesh, if it has one
  30965. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30966. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30967. * When false, achieved by calling a clone(), also passing False.
  30968. * This will make creation of children, recursive.
  30969. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30970. */
  30971. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30972. if (scene === void 0) { scene = null; }
  30973. if (parent === void 0) { parent = null; }
  30974. if (source === void 0) { source = null; }
  30975. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30976. var _this = _super.call(this, name, scene) || this;
  30977. // Members
  30978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30979. _this.instances = new Array();
  30980. _this._LODLevels = new Array();
  30981. /** @hidden */
  30982. _this._visibleInstances = {};
  30983. _this._renderIdForInstances = new Array();
  30984. _this._batchCache = new _InstancesBatch();
  30985. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30986. // Use by builder only to know what orientation were the mesh build in.
  30987. /** @hidden */
  30988. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30989. _this.overrideMaterialSideOrientation = null;
  30990. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30991. // Will be used to save a source mesh reference, If any
  30992. _this._source = null;
  30993. scene = _this.getScene();
  30994. if (source) {
  30995. // Geometry
  30996. if (source._geometry) {
  30997. source._geometry.applyToMesh(_this);
  30998. }
  30999. // Deep copy
  31000. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31001. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31002. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31003. ], ["_poseMatrix"]);
  31004. // Source mesh
  31005. _this._source = source;
  31006. // Construction Params
  31007. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31008. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31009. var myAnyThis = _this;
  31010. var myAnySource = source;
  31011. myAnyThis._closePath = myAnySource._closePath;
  31012. myAnyThis._idx = myAnySource._idx;
  31013. myAnyThis.dashSize = myAnySource.dashSize;
  31014. myAnyThis.gapSize = myAnySource.gapSize;
  31015. myAnyThis.path3D = myAnySource.path3D;
  31016. myAnyThis.pathArray = myAnySource.pathArray;
  31017. myAnyThis.arc = myAnySource.arc;
  31018. myAnyThis.radius = myAnySource.radius;
  31019. // Animation ranges
  31020. if (_this._source._ranges) {
  31021. var ranges = _this._source._ranges;
  31022. for (var name in ranges) {
  31023. if (!ranges.hasOwnProperty(name)) {
  31024. continue;
  31025. }
  31026. if (!ranges[name]) {
  31027. continue;
  31028. }
  31029. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31030. }
  31031. }
  31032. // Metadata
  31033. if (source.metadata && source.metadata.clone) {
  31034. _this.metadata = source.metadata.clone();
  31035. }
  31036. else {
  31037. _this.metadata = source.metadata;
  31038. }
  31039. // Tags
  31040. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31041. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31042. }
  31043. // Parent
  31044. _this.parent = source.parent;
  31045. // Pivot
  31046. _this.setPivotMatrix(source.getPivotMatrix());
  31047. _this.id = name + "." + source.id;
  31048. // Material
  31049. _this.material = source.material;
  31050. var index;
  31051. if (!doNotCloneChildren) {
  31052. // Children
  31053. var directDescendants = source.getDescendants(true);
  31054. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31055. var child = directDescendants[index_1];
  31056. if (child.clone) {
  31057. child.clone(name + "." + child.name, _this);
  31058. }
  31059. }
  31060. }
  31061. // Physics clone
  31062. var physicsEngine = _this.getScene().getPhysicsEngine();
  31063. if (clonePhysicsImpostor && physicsEngine) {
  31064. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31065. if (impostor) {
  31066. _this.physicsImpostor = impostor.clone(_this);
  31067. }
  31068. }
  31069. // Particles
  31070. for (index = 0; index < scene.particleSystems.length; index++) {
  31071. var system = scene.particleSystems[index];
  31072. if (system.emitter === source) {
  31073. system.clone(system.name, _this);
  31074. }
  31075. }
  31076. _this.refreshBoundingInfo();
  31077. _this.computeWorldMatrix(true);
  31078. }
  31079. // Parent
  31080. if (parent !== null) {
  31081. _this.parent = parent;
  31082. }
  31083. return _this;
  31084. }
  31085. Object.defineProperty(Mesh, "FRONTSIDE", {
  31086. /**
  31087. * Mesh side orientation : usually the external or front surface
  31088. */
  31089. get: function () {
  31090. return Mesh._FRONTSIDE;
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. Object.defineProperty(Mesh, "BACKSIDE", {
  31096. /**
  31097. * Mesh side orientation : usually the internal or back surface
  31098. */
  31099. get: function () {
  31100. return Mesh._BACKSIDE;
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31106. /**
  31107. * Mesh side orientation : both internal and external or front and back surfaces
  31108. */
  31109. get: function () {
  31110. return Mesh._DOUBLESIDE;
  31111. },
  31112. enumerable: true,
  31113. configurable: true
  31114. });
  31115. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31116. /**
  31117. * Mesh side orientation : by default, `FRONTSIDE`
  31118. */
  31119. get: function () {
  31120. return Mesh._DEFAULTSIDE;
  31121. },
  31122. enumerable: true,
  31123. configurable: true
  31124. });
  31125. Object.defineProperty(Mesh, "NO_CAP", {
  31126. /**
  31127. * Mesh cap setting : no cap
  31128. */
  31129. get: function () {
  31130. return Mesh._NO_CAP;
  31131. },
  31132. enumerable: true,
  31133. configurable: true
  31134. });
  31135. Object.defineProperty(Mesh, "CAP_START", {
  31136. /**
  31137. * Mesh cap setting : one cap at the beginning of the mesh
  31138. */
  31139. get: function () {
  31140. return Mesh._CAP_START;
  31141. },
  31142. enumerable: true,
  31143. configurable: true
  31144. });
  31145. Object.defineProperty(Mesh, "CAP_END", {
  31146. /**
  31147. * Mesh cap setting : one cap at the end of the mesh
  31148. */
  31149. get: function () {
  31150. return Mesh._CAP_END;
  31151. },
  31152. enumerable: true,
  31153. configurable: true
  31154. });
  31155. Object.defineProperty(Mesh, "CAP_ALL", {
  31156. /**
  31157. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31158. */
  31159. get: function () {
  31160. return Mesh._CAP_ALL;
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31166. /**
  31167. * An event triggered before rendering the mesh
  31168. */
  31169. get: function () {
  31170. if (!this._onBeforeRenderObservable) {
  31171. this._onBeforeRenderObservable = new BABYLON.Observable();
  31172. }
  31173. return this._onBeforeRenderObservable;
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31179. /**
  31180. * An event triggered after rendering the mesh
  31181. */
  31182. get: function () {
  31183. if (!this._onAfterRenderObservable) {
  31184. this._onAfterRenderObservable = new BABYLON.Observable();
  31185. }
  31186. return this._onAfterRenderObservable;
  31187. },
  31188. enumerable: true,
  31189. configurable: true
  31190. });
  31191. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31192. /**
  31193. * An event triggered before drawing the mesh
  31194. */
  31195. get: function () {
  31196. if (!this._onBeforeDrawObservable) {
  31197. this._onBeforeDrawObservable = new BABYLON.Observable();
  31198. }
  31199. return this._onBeforeDrawObservable;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31205. set: function (callback) {
  31206. if (this._onBeforeDrawObserver) {
  31207. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31208. }
  31209. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31210. },
  31211. enumerable: true,
  31212. configurable: true
  31213. });
  31214. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31215. get: function () {
  31216. return this._morphTargetManager;
  31217. },
  31218. set: function (value) {
  31219. if (this._morphTargetManager === value) {
  31220. return;
  31221. }
  31222. this._morphTargetManager = value;
  31223. this._syncGeometryWithMorphTargetManager();
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(Mesh.prototype, "source", {
  31229. get: function () {
  31230. return this._source;
  31231. },
  31232. enumerable: true,
  31233. configurable: true
  31234. });
  31235. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31236. get: function () {
  31237. return this._unIndexed;
  31238. },
  31239. set: function (value) {
  31240. if (this._unIndexed !== value) {
  31241. this._unIndexed = value;
  31242. this._markSubMeshesAsAttributesDirty();
  31243. }
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. // Methods
  31249. /**
  31250. * Returns the string "Mesh".
  31251. */
  31252. Mesh.prototype.getClassName = function () {
  31253. return "Mesh";
  31254. };
  31255. /**
  31256. * Returns a string.
  31257. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31258. */
  31259. Mesh.prototype.toString = function (fullDetails) {
  31260. var ret = _super.prototype.toString.call(this, fullDetails);
  31261. ret += ", n vertices: " + this.getTotalVertices();
  31262. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31263. if (this.animations) {
  31264. for (var i = 0; i < this.animations.length; i++) {
  31265. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31266. }
  31267. }
  31268. if (fullDetails) {
  31269. if (this._geometry) {
  31270. var ib = this.getIndices();
  31271. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31272. if (vb && ib) {
  31273. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31274. }
  31275. }
  31276. else {
  31277. ret += ", flat shading: UNKNOWN";
  31278. }
  31279. }
  31280. return ret;
  31281. };
  31282. /** @hidden */
  31283. Mesh.prototype._unBindEffect = function () {
  31284. _super.prototype._unBindEffect.call(this);
  31285. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31286. var instance = _a[_i];
  31287. instance._unBindEffect();
  31288. }
  31289. };
  31290. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31291. /**
  31292. * True if the mesh has some Levels Of Details (LOD).
  31293. * Returns a boolean.
  31294. */
  31295. get: function () {
  31296. return this._LODLevels.length > 0;
  31297. },
  31298. enumerable: true,
  31299. configurable: true
  31300. });
  31301. /**
  31302. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31303. * @returns an array of {BABYLON.MeshLODLevel}
  31304. */
  31305. Mesh.prototype.getLODLevels = function () {
  31306. return this._LODLevels;
  31307. };
  31308. Mesh.prototype._sortLODLevels = function () {
  31309. this._LODLevels.sort(function (a, b) {
  31310. if (a.distance < b.distance) {
  31311. return 1;
  31312. }
  31313. if (a.distance > b.distance) {
  31314. return -1;
  31315. }
  31316. return 0;
  31317. });
  31318. };
  31319. /**
  31320. * Add a mesh as LOD level triggered at the given distance.
  31321. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31322. * @param distance The distance from the center of the object to show this level
  31323. * @param mesh The mesh to be added as LOD level (can be null)
  31324. * @return This mesh (for chaining)
  31325. */
  31326. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31327. if (mesh && mesh._masterMesh) {
  31328. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31329. return this;
  31330. }
  31331. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31332. this._LODLevels.push(level);
  31333. if (mesh) {
  31334. mesh._masterMesh = this;
  31335. }
  31336. this._sortLODLevels();
  31337. return this;
  31338. };
  31339. /**
  31340. * Returns the LOD level mesh at the passed distance or null if not found.
  31341. * It is related to the method `addLODLevel(distance, mesh)`.
  31342. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31343. * Returns an object Mesh or `null`.
  31344. */
  31345. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31346. for (var index = 0; index < this._LODLevels.length; index++) {
  31347. var level = this._LODLevels[index];
  31348. if (level.distance === distance) {
  31349. return level.mesh;
  31350. }
  31351. }
  31352. return null;
  31353. };
  31354. /**
  31355. * Remove a mesh from the LOD array
  31356. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31357. * @param {Mesh} mesh The mesh to be removed.
  31358. * @return {Mesh} This mesh (for chaining)
  31359. */
  31360. Mesh.prototype.removeLODLevel = function (mesh) {
  31361. for (var index = 0; index < this._LODLevels.length; index++) {
  31362. if (this._LODLevels[index].mesh === mesh) {
  31363. this._LODLevels.splice(index, 1);
  31364. if (mesh) {
  31365. mesh._masterMesh = null;
  31366. }
  31367. }
  31368. }
  31369. this._sortLODLevels();
  31370. return this;
  31371. };
  31372. /**
  31373. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31374. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31375. */
  31376. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31377. if (!this._LODLevels || this._LODLevels.length === 0) {
  31378. return this;
  31379. }
  31380. var bSphere;
  31381. if (boundingSphere) {
  31382. bSphere = boundingSphere;
  31383. }
  31384. else {
  31385. var boundingInfo = this.getBoundingInfo();
  31386. bSphere = boundingInfo.boundingSphere;
  31387. }
  31388. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31389. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31390. if (this.onLODLevelSelection) {
  31391. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31392. }
  31393. return this;
  31394. }
  31395. for (var index = 0; index < this._LODLevels.length; index++) {
  31396. var level = this._LODLevels[index];
  31397. if (level.distance < distanceToCamera) {
  31398. if (level.mesh) {
  31399. level.mesh._preActivate();
  31400. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31401. }
  31402. if (this.onLODLevelSelection) {
  31403. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31404. }
  31405. return level.mesh;
  31406. }
  31407. }
  31408. if (this.onLODLevelSelection) {
  31409. this.onLODLevelSelection(distanceToCamera, this, this);
  31410. }
  31411. return this;
  31412. };
  31413. Object.defineProperty(Mesh.prototype, "geometry", {
  31414. /**
  31415. * Returns the mesh internal Geometry object.
  31416. */
  31417. get: function () {
  31418. return this._geometry;
  31419. },
  31420. enumerable: true,
  31421. configurable: true
  31422. });
  31423. /**
  31424. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31425. */
  31426. Mesh.prototype.getTotalVertices = function () {
  31427. if (this._geometry === null || this._geometry === undefined) {
  31428. return 0;
  31429. }
  31430. return this._geometry.getTotalVertices();
  31431. };
  31432. /**
  31433. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31434. * 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.
  31435. * You can force the copy with forceCopy === true
  31436. * Returns null if the mesh has no geometry or no vertex buffer.
  31437. * Possible `kind` values :
  31438. * - BABYLON.VertexBuffer.PositionKind
  31439. * - BABYLON.VertexBuffer.UVKind
  31440. * - BABYLON.VertexBuffer.UV2Kind
  31441. * - BABYLON.VertexBuffer.UV3Kind
  31442. * - BABYLON.VertexBuffer.UV4Kind
  31443. * - BABYLON.VertexBuffer.UV5Kind
  31444. * - BABYLON.VertexBuffer.UV6Kind
  31445. * - BABYLON.VertexBuffer.ColorKind
  31446. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31447. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31448. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31449. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31450. */
  31451. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31452. if (!this._geometry) {
  31453. return null;
  31454. }
  31455. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31456. };
  31457. /**
  31458. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31459. * Returns `null` if the mesh has no geometry.
  31460. * Possible `kind` values :
  31461. * - BABYLON.VertexBuffer.PositionKind
  31462. * - BABYLON.VertexBuffer.UVKind
  31463. * - BABYLON.VertexBuffer.UV2Kind
  31464. * - BABYLON.VertexBuffer.UV3Kind
  31465. * - BABYLON.VertexBuffer.UV4Kind
  31466. * - BABYLON.VertexBuffer.UV5Kind
  31467. * - BABYLON.VertexBuffer.UV6Kind
  31468. * - BABYLON.VertexBuffer.ColorKind
  31469. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31470. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31471. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31472. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31473. */
  31474. Mesh.prototype.getVertexBuffer = function (kind) {
  31475. if (!this._geometry) {
  31476. return null;
  31477. }
  31478. return this._geometry.getVertexBuffer(kind);
  31479. };
  31480. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31481. if (!this._geometry) {
  31482. if (this._delayInfo) {
  31483. return this._delayInfo.indexOf(kind) !== -1;
  31484. }
  31485. return false;
  31486. }
  31487. return this._geometry.isVerticesDataPresent(kind);
  31488. };
  31489. /**
  31490. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31491. * Possible `kind` values :
  31492. * - BABYLON.VertexBuffer.PositionKind
  31493. * - BABYLON.VertexBuffer.UVKind
  31494. * - BABYLON.VertexBuffer.UV2Kind
  31495. * - BABYLON.VertexBuffer.UV3Kind
  31496. * - BABYLON.VertexBuffer.UV4Kind
  31497. * - BABYLON.VertexBuffer.UV5Kind
  31498. * - BABYLON.VertexBuffer.UV6Kind
  31499. * - BABYLON.VertexBuffer.ColorKind
  31500. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31501. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31502. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31503. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31504. */
  31505. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31506. if (!this._geometry) {
  31507. if (this._delayInfo) {
  31508. return this._delayInfo.indexOf(kind) !== -1;
  31509. }
  31510. return false;
  31511. }
  31512. return this._geometry.isVertexBufferUpdatable(kind);
  31513. };
  31514. /**
  31515. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31516. * Possible `kind` values :
  31517. * - BABYLON.VertexBuffer.PositionKind
  31518. * - BABYLON.VertexBuffer.UVKind
  31519. * - BABYLON.VertexBuffer.UV2Kind
  31520. * - BABYLON.VertexBuffer.UV3Kind
  31521. * - BABYLON.VertexBuffer.UV4Kind
  31522. * - BABYLON.VertexBuffer.UV5Kind
  31523. * - BABYLON.VertexBuffer.UV6Kind
  31524. * - BABYLON.VertexBuffer.ColorKind
  31525. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31526. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31527. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31528. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31529. */
  31530. Mesh.prototype.getVerticesDataKinds = function () {
  31531. if (!this._geometry) {
  31532. var result = new Array();
  31533. if (this._delayInfo) {
  31534. this._delayInfo.forEach(function (kind, index, array) {
  31535. result.push(kind);
  31536. });
  31537. }
  31538. return result;
  31539. }
  31540. return this._geometry.getVerticesDataKinds();
  31541. };
  31542. /**
  31543. * Returns a positive integer : the total number of indices in this mesh geometry.
  31544. * Returns zero if the mesh has no geometry.
  31545. */
  31546. Mesh.prototype.getTotalIndices = function () {
  31547. if (!this._geometry) {
  31548. return 0;
  31549. }
  31550. return this._geometry.getTotalIndices();
  31551. };
  31552. /**
  31553. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31554. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31555. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31556. * @returns the indices array or an empty array if the mesh has no geometry
  31557. */
  31558. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31559. if (!this._geometry) {
  31560. return [];
  31561. }
  31562. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31563. };
  31564. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31565. get: function () {
  31566. return this._masterMesh !== null && this._masterMesh !== undefined;
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. /**
  31572. * Determine if the current mesh is ready to be rendered
  31573. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31574. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31575. * @returns true if all associated assets are ready (material, textures, shaders)
  31576. */
  31577. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31578. if (completeCheck === void 0) { completeCheck = false; }
  31579. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31580. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31581. return false;
  31582. }
  31583. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31584. return false;
  31585. }
  31586. if (!this.subMeshes || this.subMeshes.length === 0) {
  31587. return true;
  31588. }
  31589. if (!completeCheck) {
  31590. return true;
  31591. }
  31592. var engine = this.getEngine();
  31593. var scene = this.getScene();
  31594. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31595. this.computeWorldMatrix();
  31596. var mat = this.material || scene.defaultMaterial;
  31597. if (mat) {
  31598. if (mat.storeEffectOnSubMeshes) {
  31599. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31600. var subMesh = _a[_i];
  31601. var effectiveMaterial = subMesh.getMaterial();
  31602. if (effectiveMaterial) {
  31603. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31604. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31605. return false;
  31606. }
  31607. }
  31608. else {
  31609. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31610. return false;
  31611. }
  31612. }
  31613. }
  31614. }
  31615. }
  31616. else {
  31617. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31618. return false;
  31619. }
  31620. }
  31621. }
  31622. // Shadows
  31623. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31624. var light = _c[_b];
  31625. var generator = light.getShadowGenerator();
  31626. if (generator) {
  31627. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31628. var subMesh = _e[_d];
  31629. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31630. return false;
  31631. }
  31632. }
  31633. }
  31634. }
  31635. // LOD
  31636. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31637. var lod = _g[_f];
  31638. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31639. return false;
  31640. }
  31641. }
  31642. return true;
  31643. };
  31644. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31645. /**
  31646. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31647. * This property is pertinent only for updatable parametric shapes.
  31648. */
  31649. get: function () {
  31650. return this._areNormalsFrozen;
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. /**
  31656. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31657. * It has no effect at all on other shapes.
  31658. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31659. * Returns the Mesh.
  31660. */
  31661. Mesh.prototype.freezeNormals = function () {
  31662. this._areNormalsFrozen = true;
  31663. return this;
  31664. };
  31665. /**
  31666. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31667. * It has no effect at all on other shapes.
  31668. * It reactivates the mesh normals computation if it was previously frozen.
  31669. * Returns the Mesh.
  31670. */
  31671. Mesh.prototype.unfreezeNormals = function () {
  31672. this._areNormalsFrozen = false;
  31673. return this;
  31674. };
  31675. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31676. /**
  31677. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31678. */
  31679. set: function (count) {
  31680. this._overridenInstanceCount = count;
  31681. },
  31682. enumerable: true,
  31683. configurable: true
  31684. });
  31685. // Methods
  31686. /** @hidden */
  31687. Mesh.prototype._preActivate = function () {
  31688. var sceneRenderId = this.getScene().getRenderId();
  31689. if (this._preActivateId === sceneRenderId) {
  31690. return this;
  31691. }
  31692. this._preActivateId = sceneRenderId;
  31693. this._visibleInstances = null;
  31694. return this;
  31695. };
  31696. /** @hidden */
  31697. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31698. if (this._visibleInstances) {
  31699. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31700. }
  31701. return this;
  31702. };
  31703. /** @hidden */
  31704. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31705. if (!this._visibleInstances) {
  31706. this._visibleInstances = {};
  31707. this._visibleInstances.defaultRenderId = renderId;
  31708. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31709. }
  31710. if (!this._visibleInstances[renderId]) {
  31711. this._visibleInstances[renderId] = new Array();
  31712. }
  31713. this._visibleInstances[renderId].push(instance);
  31714. return this;
  31715. };
  31716. /**
  31717. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31718. * This means the mesh underlying bounding box and sphere are recomputed.
  31719. * Returns the Mesh.
  31720. */
  31721. Mesh.prototype.refreshBoundingInfo = function () {
  31722. return this._refreshBoundingInfo(false);
  31723. };
  31724. /** @hidden */
  31725. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31726. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31727. return this;
  31728. }
  31729. var data = this._getPositionData(applySkeleton);
  31730. if (data) {
  31731. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31732. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31733. }
  31734. if (this.subMeshes) {
  31735. for (var index = 0; index < this.subMeshes.length; index++) {
  31736. this.subMeshes[index].refreshBoundingInfo();
  31737. }
  31738. }
  31739. this._updateBoundingInfo();
  31740. return this;
  31741. };
  31742. Mesh.prototype._getPositionData = function (applySkeleton) {
  31743. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31744. if (data && applySkeleton && this.skeleton) {
  31745. data = BABYLON.Tools.Slice(data);
  31746. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31747. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31748. if (matricesWeightsData && matricesIndicesData) {
  31749. var needExtras = this.numBoneInfluencers > 4;
  31750. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31751. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31752. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31753. var tempVector = BABYLON.Tmp.Vector3[0];
  31754. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31755. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31756. var matWeightIdx = 0;
  31757. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31758. finalMatrix.reset();
  31759. var inf;
  31760. var weight;
  31761. for (inf = 0; inf < 4; inf++) {
  31762. weight = matricesWeightsData[matWeightIdx + inf];
  31763. if (weight > 0) {
  31764. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31765. finalMatrix.addToSelf(tempMatrix);
  31766. }
  31767. }
  31768. if (needExtras) {
  31769. for (inf = 0; inf < 4; inf++) {
  31770. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31771. if (weight > 0) {
  31772. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31773. finalMatrix.addToSelf(tempMatrix);
  31774. }
  31775. }
  31776. }
  31777. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31778. tempVector.toArray(data, index);
  31779. }
  31780. }
  31781. }
  31782. return data;
  31783. };
  31784. /** @hidden */
  31785. Mesh.prototype._createGlobalSubMesh = function (force) {
  31786. var totalVertices = this.getTotalVertices();
  31787. if (!totalVertices || !this.getIndices()) {
  31788. return null;
  31789. }
  31790. // Check if we need to recreate the submeshes
  31791. if (this.subMeshes && this.subMeshes.length > 0) {
  31792. var ib = this.getIndices();
  31793. if (!ib) {
  31794. return null;
  31795. }
  31796. var totalIndices = ib.length;
  31797. var needToRecreate = false;
  31798. if (force) {
  31799. needToRecreate = true;
  31800. }
  31801. else {
  31802. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31803. var submesh = _a[_i];
  31804. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31805. needToRecreate = true;
  31806. break;
  31807. }
  31808. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31809. needToRecreate = true;
  31810. break;
  31811. }
  31812. }
  31813. }
  31814. if (!needToRecreate) {
  31815. return this.subMeshes[0];
  31816. }
  31817. }
  31818. this.releaseSubMeshes();
  31819. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31820. };
  31821. Mesh.prototype.subdivide = function (count) {
  31822. if (count < 1) {
  31823. return;
  31824. }
  31825. var totalIndices = this.getTotalIndices();
  31826. var subdivisionSize = (totalIndices / count) | 0;
  31827. var offset = 0;
  31828. // Ensure that subdivisionSize is a multiple of 3
  31829. while (subdivisionSize % 3 !== 0) {
  31830. subdivisionSize++;
  31831. }
  31832. this.releaseSubMeshes();
  31833. for (var index = 0; index < count; index++) {
  31834. if (offset >= totalIndices) {
  31835. break;
  31836. }
  31837. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31838. offset += subdivisionSize;
  31839. }
  31840. this.synchronizeInstances();
  31841. };
  31842. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31843. if (updatable === void 0) { updatable = false; }
  31844. if (!this._geometry) {
  31845. var vertexData = new BABYLON.VertexData();
  31846. vertexData.set(data, kind);
  31847. var scene = this.getScene();
  31848. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31849. }
  31850. else {
  31851. this._geometry.setVerticesData(kind, data, updatable, stride);
  31852. }
  31853. return this;
  31854. };
  31855. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31856. if (updatable === void 0) { updatable = true; }
  31857. var vb = this.getVertexBuffer(kind);
  31858. if (!vb || vb.isUpdatable() === updatable) {
  31859. return;
  31860. }
  31861. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31862. };
  31863. /**
  31864. * Sets the mesh VertexBuffer.
  31865. * Returns the Mesh.
  31866. */
  31867. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31868. if (!this._geometry) {
  31869. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31870. }
  31871. this._geometry.setVerticesBuffer(buffer);
  31872. return this;
  31873. };
  31874. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31875. if (!this._geometry) {
  31876. return this;
  31877. }
  31878. if (!makeItUnique) {
  31879. this._geometry.updateVerticesData(kind, data, updateExtends);
  31880. }
  31881. else {
  31882. this.makeGeometryUnique();
  31883. this.updateVerticesData(kind, data, updateExtends, false);
  31884. }
  31885. return this;
  31886. };
  31887. /**
  31888. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31889. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31890. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31891. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31892. * Returns the Mesh.
  31893. */
  31894. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31895. if (computeNormals === void 0) { computeNormals = true; }
  31896. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31897. if (!positions) {
  31898. return this;
  31899. }
  31900. positionFunction(positions);
  31901. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31902. if (computeNormals) {
  31903. var indices = this.getIndices();
  31904. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31905. if (!normals) {
  31906. return this;
  31907. }
  31908. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31909. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31910. }
  31911. return this;
  31912. };
  31913. /**
  31914. * Creates a un-shared specific occurence of the geometry for the mesh.
  31915. * Returns the Mesh.
  31916. */
  31917. Mesh.prototype.makeGeometryUnique = function () {
  31918. if (!this._geometry) {
  31919. return this;
  31920. }
  31921. var oldGeometry = this._geometry;
  31922. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31923. oldGeometry.releaseForMesh(this, true);
  31924. geometry.applyToMesh(this);
  31925. return this;
  31926. };
  31927. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31928. if (totalVertices === void 0) { totalVertices = null; }
  31929. if (updatable === void 0) { updatable = false; }
  31930. if (!this._geometry) {
  31931. var vertexData = new BABYLON.VertexData();
  31932. vertexData.indices = indices;
  31933. var scene = this.getScene();
  31934. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31935. }
  31936. else {
  31937. this._geometry.setIndices(indices, totalVertices, updatable);
  31938. }
  31939. return this;
  31940. };
  31941. /**
  31942. * Update the current index buffer
  31943. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31944. * Returns the Mesh.
  31945. */
  31946. Mesh.prototype.updateIndices = function (indices, offset) {
  31947. if (!this._geometry) {
  31948. return this;
  31949. }
  31950. this._geometry.updateIndices(indices, offset);
  31951. return this;
  31952. };
  31953. /**
  31954. * Invert the geometry to move from a right handed system to a left handed one.
  31955. * Returns the Mesh.
  31956. */
  31957. Mesh.prototype.toLeftHanded = function () {
  31958. if (!this._geometry) {
  31959. return this;
  31960. }
  31961. this._geometry.toLeftHanded();
  31962. return this;
  31963. };
  31964. /** @hidden */
  31965. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31966. if (!this._geometry) {
  31967. return this;
  31968. }
  31969. var engine = this.getScene().getEngine();
  31970. // Wireframe
  31971. var indexToBind;
  31972. if (this._unIndexed) {
  31973. indexToBind = null;
  31974. }
  31975. else {
  31976. switch (fillMode) {
  31977. case BABYLON.Material.PointFillMode:
  31978. indexToBind = null;
  31979. break;
  31980. case BABYLON.Material.WireFrameFillMode:
  31981. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31982. break;
  31983. default:
  31984. case BABYLON.Material.TriangleFillMode:
  31985. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31986. break;
  31987. }
  31988. }
  31989. // VBOs
  31990. this._geometry._bind(effect, indexToBind);
  31991. return this;
  31992. };
  31993. /** @hidden */
  31994. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31995. if (alternate === void 0) { alternate = false; }
  31996. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31997. return this;
  31998. }
  31999. if (this._onBeforeDrawObservable) {
  32000. this._onBeforeDrawObservable.notifyObservers(this);
  32001. }
  32002. var scene = this.getScene();
  32003. var engine = scene.getEngine();
  32004. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32005. // or triangles as points
  32006. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32007. }
  32008. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32009. // Triangles as wireframe
  32010. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32011. }
  32012. else {
  32013. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32014. }
  32015. if (scene._isAlternateRenderingEnabled && !alternate) {
  32016. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32017. if (!effect || !scene.activeCamera) {
  32018. return this;
  32019. }
  32020. scene._switchToAlternateCameraConfiguration(true);
  32021. this._effectiveMaterial.bindView(effect);
  32022. this._effectiveMaterial.bindViewProjection(effect);
  32023. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32024. this._draw(subMesh, fillMode, instancesCount, true);
  32025. engine.setViewport(scene.activeCamera.viewport);
  32026. scene._switchToAlternateCameraConfiguration(false);
  32027. this._effectiveMaterial.bindView(effect);
  32028. this._effectiveMaterial.bindViewProjection(effect);
  32029. }
  32030. return this;
  32031. };
  32032. /**
  32033. * Registers for this mesh a javascript function called just before the rendering process.
  32034. * This function is passed the current mesh.
  32035. * Return the Mesh.
  32036. */
  32037. Mesh.prototype.registerBeforeRender = function (func) {
  32038. this.onBeforeRenderObservable.add(func);
  32039. return this;
  32040. };
  32041. /**
  32042. * Disposes a previously registered javascript function called before the rendering.
  32043. * This function is passed the current mesh.
  32044. * Returns the Mesh.
  32045. */
  32046. Mesh.prototype.unregisterBeforeRender = function (func) {
  32047. this.onBeforeRenderObservable.removeCallback(func);
  32048. return this;
  32049. };
  32050. /**
  32051. * Registers for this mesh a javascript function called just after the rendering is complete.
  32052. * This function is passed the current mesh.
  32053. * Returns the Mesh.
  32054. */
  32055. Mesh.prototype.registerAfterRender = function (func) {
  32056. this.onAfterRenderObservable.add(func);
  32057. return this;
  32058. };
  32059. /**
  32060. * Disposes a previously registered javascript function called after the rendering.
  32061. * This function is passed the current mesh.
  32062. * Return the Mesh.
  32063. */
  32064. Mesh.prototype.unregisterAfterRender = function (func) {
  32065. this.onAfterRenderObservable.removeCallback(func);
  32066. return this;
  32067. };
  32068. /** @hidden */
  32069. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32070. var scene = this.getScene();
  32071. this._batchCache.mustReturn = false;
  32072. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32073. this._batchCache.visibleInstances[subMeshId] = null;
  32074. if (this._visibleInstances) {
  32075. var currentRenderId = scene.getRenderId();
  32076. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32077. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32078. var selfRenderId = this._renderId;
  32079. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32080. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32081. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32082. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32083. }
  32084. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32085. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32086. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32087. this._batchCache.mustReturn = true;
  32088. return this._batchCache;
  32089. }
  32090. if (currentRenderId !== selfRenderId) {
  32091. this._batchCache.renderSelf[subMeshId] = false;
  32092. }
  32093. }
  32094. this._renderIdForInstances[subMeshId] = currentRenderId;
  32095. }
  32096. return this._batchCache;
  32097. };
  32098. /** @hidden */
  32099. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32100. var visibleInstances = batch.visibleInstances[subMesh._id];
  32101. if (!visibleInstances) {
  32102. return this;
  32103. }
  32104. var matricesCount = visibleInstances.length + 1;
  32105. var bufferSize = matricesCount * 16 * 4;
  32106. var currentInstancesBufferSize = this._instancesBufferSize;
  32107. var instancesBuffer = this._instancesBuffer;
  32108. while (this._instancesBufferSize < bufferSize) {
  32109. this._instancesBufferSize *= 2;
  32110. }
  32111. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32112. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32113. }
  32114. var offset = 0;
  32115. var instancesCount = 0;
  32116. var world = this.getWorldMatrix();
  32117. if (batch.renderSelf[subMesh._id]) {
  32118. world.copyToArray(this._instancesData, offset);
  32119. offset += 16;
  32120. instancesCount++;
  32121. }
  32122. if (visibleInstances) {
  32123. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32124. var instance = visibleInstances[instanceIndex];
  32125. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32126. offset += 16;
  32127. instancesCount++;
  32128. }
  32129. }
  32130. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32131. if (instancesBuffer) {
  32132. instancesBuffer.dispose();
  32133. }
  32134. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32135. this._instancesBuffer = instancesBuffer;
  32136. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32137. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32138. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32139. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32140. }
  32141. else {
  32142. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32143. }
  32144. this._bind(subMesh, effect, fillMode);
  32145. this._draw(subMesh, fillMode, instancesCount);
  32146. engine.unbindInstanceAttributes();
  32147. return this;
  32148. };
  32149. /** @hidden */
  32150. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32151. var scene = this.getScene();
  32152. var engine = scene.getEngine();
  32153. if (hardwareInstancedRendering) {
  32154. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32155. }
  32156. else {
  32157. if (batch.renderSelf[subMesh._id]) {
  32158. // Draw
  32159. if (onBeforeDraw) {
  32160. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32161. }
  32162. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32163. }
  32164. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32165. if (visibleInstancesForSubMesh) {
  32166. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32167. var instance = visibleInstancesForSubMesh[instanceIndex];
  32168. // World
  32169. var world = instance.getWorldMatrix();
  32170. if (onBeforeDraw) {
  32171. onBeforeDraw(true, world, effectiveMaterial);
  32172. }
  32173. // Draw
  32174. this._draw(subMesh, fillMode);
  32175. }
  32176. }
  32177. }
  32178. return this;
  32179. };
  32180. /**
  32181. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32182. * @param subMesh defines the subMesh to render
  32183. * @param enableAlphaMode defines if alpha mode can be changed
  32184. * @returns the current mesh
  32185. */
  32186. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32187. this._checkOcclusionQuery();
  32188. if (this._isOccluded) {
  32189. return this;
  32190. }
  32191. var scene = this.getScene();
  32192. // Managing instances
  32193. var batch = this._getInstancesRenderList(subMesh._id);
  32194. if (batch.mustReturn) {
  32195. return this;
  32196. }
  32197. // Checking geometry state
  32198. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32199. return this;
  32200. }
  32201. if (this._onBeforeRenderObservable) {
  32202. this._onBeforeRenderObservable.notifyObservers(this);
  32203. }
  32204. var engine = scene.getEngine();
  32205. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32206. // Material
  32207. var material = subMesh.getMaterial();
  32208. if (!material) {
  32209. return this;
  32210. }
  32211. this._effectiveMaterial = material;
  32212. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32213. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32214. return this;
  32215. }
  32216. }
  32217. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32218. return this;
  32219. }
  32220. // Alpha mode
  32221. if (enableAlphaMode) {
  32222. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32223. }
  32224. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32225. var step = _a[_i];
  32226. step.action(this, subMesh, batch);
  32227. }
  32228. var effect;
  32229. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32230. effect = subMesh.effect;
  32231. }
  32232. else {
  32233. effect = this._effectiveMaterial.getEffect();
  32234. }
  32235. if (!effect) {
  32236. return this;
  32237. }
  32238. var sideOrientation = this.overrideMaterialSideOrientation;
  32239. if (sideOrientation == null) {
  32240. sideOrientation = this._effectiveMaterial.sideOrientation;
  32241. if (this._getWorldMatrixDeterminant() < 0) {
  32242. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32243. }
  32244. }
  32245. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32246. if (this._effectiveMaterial.forceDepthWrite) {
  32247. engine.setDepthWrite(true);
  32248. }
  32249. // Bind
  32250. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32251. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32252. this._bind(subMesh, effect, fillMode);
  32253. }
  32254. var world = this.getWorldMatrix();
  32255. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32256. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32257. }
  32258. else {
  32259. this._effectiveMaterial.bind(world, this);
  32260. }
  32261. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32262. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32263. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32264. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32265. }
  32266. // Draw
  32267. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32268. // Unbind
  32269. this._effectiveMaterial.unbind();
  32270. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32271. var step = _c[_b];
  32272. step.action(this, subMesh, batch);
  32273. }
  32274. if (this._onAfterRenderObservable) {
  32275. this._onAfterRenderObservable.notifyObservers(this);
  32276. }
  32277. return this;
  32278. };
  32279. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32280. if (isInstance && effectiveMaterial) {
  32281. effectiveMaterial.bindOnlyWorldMatrix(world);
  32282. }
  32283. };
  32284. /**
  32285. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32286. */
  32287. Mesh.prototype.getEmittedParticleSystems = function () {
  32288. var results = new Array();
  32289. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32290. var particleSystem = this.getScene().particleSystems[index];
  32291. if (particleSystem.emitter === this) {
  32292. results.push(particleSystem);
  32293. }
  32294. }
  32295. return results;
  32296. };
  32297. /**
  32298. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32299. */
  32300. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32301. var results = new Array();
  32302. var descendants = this.getDescendants();
  32303. descendants.push(this);
  32304. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32305. var particleSystem = this.getScene().particleSystems[index];
  32306. var emitter = particleSystem.emitter;
  32307. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32308. results.push(particleSystem);
  32309. }
  32310. }
  32311. return results;
  32312. };
  32313. /**
  32314. * Normalize matrix weights so that all vertices have a total weight set to 1
  32315. */
  32316. Mesh.prototype.cleanMatrixWeights = function () {
  32317. var epsilon = 1e-3;
  32318. var noInfluenceBoneIndex = 0.0;
  32319. if (this.skeleton) {
  32320. noInfluenceBoneIndex = this.skeleton.bones.length;
  32321. }
  32322. else {
  32323. return;
  32324. }
  32325. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32326. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32327. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32328. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32329. var influencers = this.numBoneInfluencers;
  32330. var size = matricesWeights.length;
  32331. for (var i = 0; i < size; i += 4) {
  32332. var weight = 0.0;
  32333. var firstZeroWeight = -1;
  32334. for (var j = 0; j < 4; j++) {
  32335. var w = matricesWeights[i + j];
  32336. weight += w;
  32337. if (w < epsilon && firstZeroWeight < 0) {
  32338. firstZeroWeight = j;
  32339. }
  32340. }
  32341. if (matricesWeightsExtra) {
  32342. for (var j = 0; j < 4; j++) {
  32343. var w = matricesWeightsExtra[i + j];
  32344. weight += w;
  32345. if (w < epsilon && firstZeroWeight < 0) {
  32346. firstZeroWeight = j + 4;
  32347. }
  32348. }
  32349. }
  32350. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32351. firstZeroWeight = influencers - 1;
  32352. }
  32353. if (weight > epsilon) {
  32354. var mweight = 1.0 / weight;
  32355. for (var j = 0; j < 4; j++) {
  32356. matricesWeights[i + j] *= mweight;
  32357. }
  32358. if (matricesWeightsExtra) {
  32359. for (var j = 0; j < 4; j++) {
  32360. matricesWeightsExtra[i + j] *= mweight;
  32361. }
  32362. }
  32363. }
  32364. else {
  32365. if (firstZeroWeight >= 4) {
  32366. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32367. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32368. }
  32369. else {
  32370. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32371. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32372. }
  32373. }
  32374. }
  32375. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32376. if (matricesIndicesExtra) {
  32377. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32378. }
  32379. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32380. if (matricesWeightsExtra) {
  32381. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32382. }
  32383. };
  32384. /** @hidden */
  32385. Mesh.prototype._checkDelayState = function () {
  32386. var scene = this.getScene();
  32387. if (this._geometry) {
  32388. this._geometry.load(scene);
  32389. }
  32390. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32392. this._queueLoad(scene);
  32393. }
  32394. return this;
  32395. };
  32396. Mesh.prototype._queueLoad = function (scene) {
  32397. var _this = this;
  32398. scene._addPendingData(this);
  32399. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32400. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32401. if (data instanceof ArrayBuffer) {
  32402. _this._delayLoadingFunction(data, _this);
  32403. }
  32404. else {
  32405. _this._delayLoadingFunction(JSON.parse(data), _this);
  32406. }
  32407. _this.instances.forEach(function (instance) {
  32408. instance._syncSubMeshes();
  32409. });
  32410. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32411. scene._removePendingData(_this);
  32412. }, function () { }, scene.database, getBinaryData);
  32413. return this;
  32414. };
  32415. /**
  32416. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32417. * A mesh is in the frustum if its bounding box intersects the frustum
  32418. * @param frustumPlanes defines the frustum to test
  32419. * @returns true if the mesh is in the frustum planes
  32420. */
  32421. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32422. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32423. return false;
  32424. }
  32425. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32426. return false;
  32427. }
  32428. this._checkDelayState();
  32429. return true;
  32430. };
  32431. /**
  32432. * Sets the mesh material by the material or multiMaterial `id` property.
  32433. * The material `id` is a string identifying the material or the multiMaterial.
  32434. * This method returns the Mesh.
  32435. */
  32436. Mesh.prototype.setMaterialByID = function (id) {
  32437. var materials = this.getScene().materials;
  32438. var index;
  32439. for (index = materials.length - 1; index > -1; index--) {
  32440. if (materials[index].id === id) {
  32441. this.material = materials[index];
  32442. return this;
  32443. }
  32444. }
  32445. // Multi
  32446. var multiMaterials = this.getScene().multiMaterials;
  32447. for (index = multiMaterials.length - 1; index > -1; index--) {
  32448. if (multiMaterials[index].id === id) {
  32449. this.material = multiMaterials[index];
  32450. return this;
  32451. }
  32452. }
  32453. return this;
  32454. };
  32455. /**
  32456. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32457. */
  32458. Mesh.prototype.getAnimatables = function () {
  32459. var results = new Array();
  32460. if (this.material) {
  32461. results.push(this.material);
  32462. }
  32463. if (this.skeleton) {
  32464. results.push(this.skeleton);
  32465. }
  32466. return results;
  32467. };
  32468. /**
  32469. * Modifies the mesh geometry according to the passed transformation matrix.
  32470. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32471. * The mesh normals are modified using the same transformation.
  32472. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32473. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32474. * Returns the Mesh.
  32475. */
  32476. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32477. // Position
  32478. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32479. return this;
  32480. }
  32481. var submeshes = this.subMeshes.splice(0);
  32482. this._resetPointsArrayCache();
  32483. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32484. var temp = new Array();
  32485. var index;
  32486. for (index = 0; index < data.length; index += 3) {
  32487. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32488. }
  32489. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32490. // Normals
  32491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32492. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32493. temp = [];
  32494. for (index = 0; index < data.length; index += 3) {
  32495. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32496. }
  32497. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32498. }
  32499. // flip faces?
  32500. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32501. this.flipFaces();
  32502. }
  32503. // Restore submeshes
  32504. this.releaseSubMeshes();
  32505. this.subMeshes = submeshes;
  32506. return this;
  32507. };
  32508. /**
  32509. * Modifies the mesh geometry according to its own current World Matrix.
  32510. * The mesh World Matrix is then reset.
  32511. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32512. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32513. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32514. * Returns the Mesh.
  32515. */
  32516. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32517. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32518. this.scaling.copyFromFloats(1, 1, 1);
  32519. this.position.copyFromFloats(0, 0, 0);
  32520. this.rotation.copyFromFloats(0, 0, 0);
  32521. //only if quaternion is already set
  32522. if (this.rotationQuaternion) {
  32523. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32524. }
  32525. this._worldMatrix = BABYLON.Matrix.Identity();
  32526. return this;
  32527. };
  32528. Object.defineProperty(Mesh.prototype, "_positions", {
  32529. // Cache
  32530. get: function () {
  32531. if (this._geometry) {
  32532. return this._geometry._positions;
  32533. }
  32534. return null;
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. /** @hidden */
  32540. Mesh.prototype._resetPointsArrayCache = function () {
  32541. if (this._geometry) {
  32542. this._geometry._resetPointsArrayCache();
  32543. }
  32544. return this;
  32545. };
  32546. /** @hidden */
  32547. Mesh.prototype._generatePointsArray = function () {
  32548. if (this._geometry) {
  32549. return this._geometry._generatePointsArray();
  32550. }
  32551. return false;
  32552. };
  32553. /**
  32554. * Returns a new Mesh object generated from the current mesh properties.
  32555. * This method must not get confused with createInstance().
  32556. * The parameter `name` is a string, the name given to the new mesh.
  32557. * The optional parameter `newParent` can be any Node object (default `null`).
  32558. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32559. * 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.
  32560. */
  32561. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32562. if (name === void 0) { name = ""; }
  32563. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32564. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32565. };
  32566. /**
  32567. * Releases resources associated with this mesh.
  32568. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32569. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32570. */
  32571. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32572. var _this = this;
  32573. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32574. this.morphTargetManager = null;
  32575. if (this._geometry) {
  32576. this._geometry.releaseForMesh(this, true);
  32577. }
  32578. if (this._onBeforeDrawObservable) {
  32579. this._onBeforeDrawObservable.clear();
  32580. }
  32581. if (this._onBeforeRenderObservable) {
  32582. this._onBeforeRenderObservable.clear();
  32583. }
  32584. if (this._onAfterRenderObservable) {
  32585. this._onAfterRenderObservable.clear();
  32586. }
  32587. // Sources
  32588. var meshes = this.getScene().meshes;
  32589. meshes.forEach(function (abstractMesh) {
  32590. var mesh = abstractMesh;
  32591. if (mesh._source && mesh._source === _this) {
  32592. mesh._source = null;
  32593. }
  32594. });
  32595. this._source = null;
  32596. // Instances
  32597. if (this._instancesBuffer) {
  32598. this._instancesBuffer.dispose();
  32599. this._instancesBuffer = null;
  32600. }
  32601. while (this.instances.length) {
  32602. this.instances[0].dispose();
  32603. }
  32604. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32605. };
  32606. /**
  32607. * Modifies the mesh geometry according to a displacement map.
  32608. * 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.
  32609. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32610. * This method returns nothing.
  32611. * @param url is a string, the URL from the image file is to be downloaded.
  32612. * @param minHeight is the lower limit of the displacement.
  32613. * @param maxHeight is the upper limit of the displacement.
  32614. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32615. * @param uvOffset is an optional vector2 used to offset UV.
  32616. * @param uvScale is an optional vector2 used to scale UV.
  32617. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32618. * @returns the Mesh.
  32619. */
  32620. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32621. var _this = this;
  32622. if (forceUpdate === void 0) { forceUpdate = false; }
  32623. var scene = this.getScene();
  32624. var onload = function (img) {
  32625. // Getting height map data
  32626. var canvas = document.createElement("canvas");
  32627. var context = canvas.getContext("2d");
  32628. var heightMapWidth = img.width;
  32629. var heightMapHeight = img.height;
  32630. canvas.width = heightMapWidth;
  32631. canvas.height = heightMapHeight;
  32632. context.drawImage(img, 0, 0);
  32633. // Create VertexData from map data
  32634. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32635. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32636. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32637. //execute success callback, if set
  32638. if (onSuccess) {
  32639. onSuccess(_this);
  32640. }
  32641. };
  32642. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32643. return this;
  32644. };
  32645. /**
  32646. * Modifies the mesh geometry according to a displacementMap buffer.
  32647. * 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.
  32648. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32649. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32650. * @param heightMapWidth is the width of the buffer image.
  32651. * @param heightMapHeight is the height of the buffer image.
  32652. * @param minHeight is the lower limit of the displacement.
  32653. * @param maxHeight is the upper limit of the displacement.
  32654. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32655. * @param uvOffset is an optional vector2 used to offset UV.
  32656. * @param uvScale is an optional vector2 used to scale UV.
  32657. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32658. * @returns the Mesh.
  32659. */
  32660. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32661. if (forceUpdate === void 0) { forceUpdate = false; }
  32662. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32663. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32664. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32665. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32666. return this;
  32667. }
  32668. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32669. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32670. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32671. var position = BABYLON.Vector3.Zero();
  32672. var normal = BABYLON.Vector3.Zero();
  32673. var uv = BABYLON.Vector2.Zero();
  32674. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32675. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32676. for (var index = 0; index < positions.length; index += 3) {
  32677. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32678. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32679. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32680. // Compute height
  32681. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32682. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32683. var pos = (u + v * heightMapWidth) * 4;
  32684. var r = buffer[pos] / 255.0;
  32685. var g = buffer[pos + 1] / 255.0;
  32686. var b = buffer[pos + 2] / 255.0;
  32687. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32688. normal.normalize();
  32689. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32690. position = position.add(normal);
  32691. position.toArray(positions, index);
  32692. }
  32693. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32694. if (forceUpdate) {
  32695. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32696. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32697. }
  32698. else {
  32699. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32700. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32701. }
  32702. return this;
  32703. };
  32704. /**
  32705. * Modify the mesh to get a flat shading rendering.
  32706. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32707. * This method returns the Mesh.
  32708. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32709. */
  32710. Mesh.prototype.convertToFlatShadedMesh = function () {
  32711. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32712. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32713. var kinds = this.getVerticesDataKinds();
  32714. var vbs = {};
  32715. var data = {};
  32716. var newdata = {};
  32717. var updatableNormals = false;
  32718. var kindIndex;
  32719. var kind;
  32720. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32721. kind = kinds[kindIndex];
  32722. var vertexBuffer = this.getVertexBuffer(kind);
  32723. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32724. updatableNormals = vertexBuffer.isUpdatable();
  32725. kinds.splice(kindIndex, 1);
  32726. kindIndex--;
  32727. continue;
  32728. }
  32729. vbs[kind] = vertexBuffer;
  32730. data[kind] = vbs[kind].getData();
  32731. newdata[kind] = [];
  32732. }
  32733. // Save previous submeshes
  32734. var previousSubmeshes = this.subMeshes.slice(0);
  32735. var indices = this.getIndices();
  32736. var totalIndices = this.getTotalIndices();
  32737. // Generating unique vertices per face
  32738. var index;
  32739. for (index = 0; index < totalIndices; index++) {
  32740. var vertexIndex = indices[index];
  32741. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32742. kind = kinds[kindIndex];
  32743. var stride = vbs[kind].getStrideSize();
  32744. for (var offset = 0; offset < stride; offset++) {
  32745. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32746. }
  32747. }
  32748. }
  32749. // Updating faces & normal
  32750. var normals = [];
  32751. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32752. for (index = 0; index < totalIndices; index += 3) {
  32753. indices[index] = index;
  32754. indices[index + 1] = index + 1;
  32755. indices[index + 2] = index + 2;
  32756. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32757. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32758. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32759. var p1p2 = p1.subtract(p2);
  32760. var p3p2 = p3.subtract(p2);
  32761. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32762. // Store same normals for every vertex
  32763. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32764. normals.push(normal.x);
  32765. normals.push(normal.y);
  32766. normals.push(normal.z);
  32767. }
  32768. }
  32769. this.setIndices(indices);
  32770. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32771. // Updating vertex buffers
  32772. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32773. kind = kinds[kindIndex];
  32774. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32775. }
  32776. // Updating submeshes
  32777. this.releaseSubMeshes();
  32778. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32779. var previousOne = previousSubmeshes[submeshIndex];
  32780. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32781. }
  32782. this.synchronizeInstances();
  32783. return this;
  32784. };
  32785. /**
  32786. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32787. * In other words, more vertices, no more indices and a single bigger VBO.
  32788. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32789. * Returns the Mesh.
  32790. */
  32791. Mesh.prototype.convertToUnIndexedMesh = function () {
  32792. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32793. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32794. var kinds = this.getVerticesDataKinds();
  32795. var vbs = {};
  32796. var data = {};
  32797. var newdata = {};
  32798. var kindIndex;
  32799. var kind;
  32800. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32801. kind = kinds[kindIndex];
  32802. var vertexBuffer = this.getVertexBuffer(kind);
  32803. vbs[kind] = vertexBuffer;
  32804. data[kind] = vbs[kind].getData();
  32805. newdata[kind] = [];
  32806. }
  32807. // Save previous submeshes
  32808. var previousSubmeshes = this.subMeshes.slice(0);
  32809. var indices = this.getIndices();
  32810. var totalIndices = this.getTotalIndices();
  32811. // Generating unique vertices per face
  32812. var index;
  32813. for (index = 0; index < totalIndices; index++) {
  32814. var vertexIndex = indices[index];
  32815. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32816. kind = kinds[kindIndex];
  32817. var stride = vbs[kind].getStrideSize();
  32818. for (var offset = 0; offset < stride; offset++) {
  32819. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32820. }
  32821. }
  32822. }
  32823. // Updating indices
  32824. for (index = 0; index < totalIndices; index += 3) {
  32825. indices[index] = index;
  32826. indices[index + 1] = index + 1;
  32827. indices[index + 2] = index + 2;
  32828. }
  32829. this.setIndices(indices);
  32830. // Updating vertex buffers
  32831. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32832. kind = kinds[kindIndex];
  32833. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32834. }
  32835. // Updating submeshes
  32836. this.releaseSubMeshes();
  32837. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32838. var previousOne = previousSubmeshes[submeshIndex];
  32839. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32840. }
  32841. this._unIndexed = true;
  32842. this.synchronizeInstances();
  32843. return this;
  32844. };
  32845. /**
  32846. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32847. * This method returns the Mesh.
  32848. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32849. */
  32850. Mesh.prototype.flipFaces = function (flipNormals) {
  32851. if (flipNormals === void 0) { flipNormals = false; }
  32852. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32853. var i;
  32854. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32855. for (i = 0; i < vertex_data.normals.length; i++) {
  32856. vertex_data.normals[i] *= -1;
  32857. }
  32858. }
  32859. if (vertex_data.indices) {
  32860. var temp;
  32861. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32862. // reassign indices
  32863. temp = vertex_data.indices[i + 1];
  32864. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32865. vertex_data.indices[i + 2] = temp;
  32866. }
  32867. }
  32868. vertex_data.applyToMesh(this);
  32869. return this;
  32870. };
  32871. // Instances
  32872. /**
  32873. * Creates a new InstancedMesh object from the mesh model.
  32874. * An instance shares the same properties and the same material than its model.
  32875. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32876. * Only these properties of each instance can then be set individually :
  32877. * - position
  32878. * - rotation
  32879. * - rotationQuaternion
  32880. * - setPivotMatrix
  32881. * - scaling
  32882. *
  32883. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32884. * Warning : this method is not supported for Line mesh and LineSystem
  32885. */
  32886. Mesh.prototype.createInstance = function (name) {
  32887. return new BABYLON.InstancedMesh(name, this);
  32888. };
  32889. /**
  32890. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32891. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32892. * This method returns the Mesh.
  32893. */
  32894. Mesh.prototype.synchronizeInstances = function () {
  32895. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32896. var instance = this.instances[instanceIndex];
  32897. instance._syncSubMeshes();
  32898. }
  32899. return this;
  32900. };
  32901. /**
  32902. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32903. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32904. * This should be used together with the simplification to avoid disappearing triangles.
  32905. * Returns the Mesh.
  32906. * @param successCallback an optional success callback to be called after the optimization finished.
  32907. */
  32908. Mesh.prototype.optimizeIndices = function (successCallback) {
  32909. var _this = this;
  32910. var indices = this.getIndices();
  32911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32912. if (!positions || !indices) {
  32913. return this;
  32914. }
  32915. var vectorPositions = new Array();
  32916. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32917. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32918. }
  32919. var dupes = new Array();
  32920. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32921. var realPos = vectorPositions.length - 1 - iteration;
  32922. var testedPosition = vectorPositions[realPos];
  32923. for (var j = 0; j < realPos; ++j) {
  32924. var againstPosition = vectorPositions[j];
  32925. if (testedPosition.equals(againstPosition)) {
  32926. dupes[realPos] = j;
  32927. break;
  32928. }
  32929. }
  32930. }, function () {
  32931. for (var i = 0; i < indices.length; ++i) {
  32932. indices[i] = dupes[indices[i]] || indices[i];
  32933. }
  32934. //indices are now reordered
  32935. var originalSubMeshes = _this.subMeshes.slice(0);
  32936. _this.setIndices(indices);
  32937. _this.subMeshes = originalSubMeshes;
  32938. if (successCallback) {
  32939. successCallback(_this);
  32940. }
  32941. });
  32942. return this;
  32943. };
  32944. Mesh.prototype.serialize = function (serializationObject) {
  32945. serializationObject.name = this.name;
  32946. serializationObject.id = this.id;
  32947. serializationObject.type = this.getClassName();
  32948. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32949. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32950. }
  32951. serializationObject.position = this.position.asArray();
  32952. if (this.rotationQuaternion) {
  32953. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32954. }
  32955. else if (this.rotation) {
  32956. serializationObject.rotation = this.rotation.asArray();
  32957. }
  32958. serializationObject.scaling = this.scaling.asArray();
  32959. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32960. serializationObject.isEnabled = this.isEnabled(false);
  32961. serializationObject.isVisible = this.isVisible;
  32962. serializationObject.infiniteDistance = this.infiniteDistance;
  32963. serializationObject.pickable = this.isPickable;
  32964. serializationObject.receiveShadows = this.receiveShadows;
  32965. serializationObject.billboardMode = this.billboardMode;
  32966. serializationObject.visibility = this.visibility;
  32967. serializationObject.checkCollisions = this.checkCollisions;
  32968. serializationObject.isBlocker = this.isBlocker;
  32969. // Parent
  32970. if (this.parent) {
  32971. serializationObject.parentId = this.parent.id;
  32972. }
  32973. // Geometry
  32974. serializationObject.isUnIndexed = this.isUnIndexed;
  32975. var geometry = this._geometry;
  32976. if (geometry) {
  32977. var geometryId = geometry.id;
  32978. serializationObject.geometryId = geometryId;
  32979. // SubMeshes
  32980. serializationObject.subMeshes = [];
  32981. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32982. var subMesh = this.subMeshes[subIndex];
  32983. serializationObject.subMeshes.push({
  32984. materialIndex: subMesh.materialIndex,
  32985. verticesStart: subMesh.verticesStart,
  32986. verticesCount: subMesh.verticesCount,
  32987. indexStart: subMesh.indexStart,
  32988. indexCount: subMesh.indexCount
  32989. });
  32990. }
  32991. }
  32992. // Material
  32993. if (this.material) {
  32994. serializationObject.materialId = this.material.id;
  32995. }
  32996. else {
  32997. this.material = null;
  32998. }
  32999. // Morph targets
  33000. if (this.morphTargetManager) {
  33001. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33002. }
  33003. // Skeleton
  33004. if (this.skeleton) {
  33005. serializationObject.skeletonId = this.skeleton.id;
  33006. }
  33007. // Physics
  33008. //TODO implement correct serialization for physics impostors.
  33009. var impostor = this.getPhysicsImpostor();
  33010. if (impostor) {
  33011. serializationObject.physicsMass = impostor.getParam("mass");
  33012. serializationObject.physicsFriction = impostor.getParam("friction");
  33013. serializationObject.physicsRestitution = impostor.getParam("mass");
  33014. serializationObject.physicsImpostor = impostor.type;
  33015. }
  33016. // Metadata
  33017. if (this.metadata) {
  33018. serializationObject.metadata = this.metadata;
  33019. }
  33020. // Instances
  33021. serializationObject.instances = [];
  33022. for (var index = 0; index < this.instances.length; index++) {
  33023. var instance = this.instances[index];
  33024. if (instance.doNotSerialize) {
  33025. continue;
  33026. }
  33027. var serializationInstance = {
  33028. name: instance.name,
  33029. id: instance.id,
  33030. position: instance.position.asArray(),
  33031. scaling: instance.scaling.asArray()
  33032. };
  33033. if (instance.parent) {
  33034. serializationInstance.parentId = instance.parent.id;
  33035. }
  33036. if (instance.rotationQuaternion) {
  33037. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33038. }
  33039. else if (instance.rotation) {
  33040. serializationInstance.rotation = instance.rotation.asArray();
  33041. }
  33042. serializationObject.instances.push(serializationInstance);
  33043. // Animations
  33044. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33045. serializationInstance.ranges = instance.serializeAnimationRanges();
  33046. }
  33047. //
  33048. // Animations
  33049. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33050. serializationObject.ranges = this.serializeAnimationRanges();
  33051. // Layer mask
  33052. serializationObject.layerMask = this.layerMask;
  33053. // Alpha
  33054. serializationObject.alphaIndex = this.alphaIndex;
  33055. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33056. // Overlay
  33057. serializationObject.overlayAlpha = this.overlayAlpha;
  33058. serializationObject.overlayColor = this.overlayColor.asArray();
  33059. serializationObject.renderOverlay = this.renderOverlay;
  33060. // Fog
  33061. serializationObject.applyFog = this.applyFog;
  33062. // Action Manager
  33063. if (this.actionManager) {
  33064. serializationObject.actions = this.actionManager.serialize(this.name);
  33065. }
  33066. };
  33067. /** @hidden */
  33068. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33069. if (!this.geometry) {
  33070. return;
  33071. }
  33072. this._markSubMeshesAsAttributesDirty();
  33073. var morphTargetManager = this._morphTargetManager;
  33074. if (morphTargetManager && morphTargetManager.vertexCount) {
  33075. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33076. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33077. this.morphTargetManager = null;
  33078. return;
  33079. }
  33080. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33081. var morphTarget = morphTargetManager.getActiveTarget(index);
  33082. var positions = morphTarget.getPositions();
  33083. if (!positions) {
  33084. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33085. return;
  33086. }
  33087. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33088. var normals = morphTarget.getNormals();
  33089. if (normals) {
  33090. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33091. }
  33092. var tangents = morphTarget.getTangents();
  33093. if (tangents) {
  33094. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33095. }
  33096. }
  33097. }
  33098. else {
  33099. var index = 0;
  33100. // Positions
  33101. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33102. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33103. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33104. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33105. }
  33106. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33107. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33108. }
  33109. index++;
  33110. }
  33111. }
  33112. };
  33113. // Statics
  33114. /**
  33115. * Returns a new Mesh object parsed from the source provided.
  33116. * The parameter `parsedMesh` is the source.
  33117. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33118. */
  33119. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33120. var mesh;
  33121. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33122. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33123. }
  33124. else {
  33125. mesh = new Mesh(parsedMesh.name, scene);
  33126. }
  33127. mesh.id = parsedMesh.id;
  33128. if (BABYLON.Tags) {
  33129. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33130. }
  33131. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33132. if (parsedMesh.metadata !== undefined) {
  33133. mesh.metadata = parsedMesh.metadata;
  33134. }
  33135. if (parsedMesh.rotationQuaternion) {
  33136. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33137. }
  33138. else if (parsedMesh.rotation) {
  33139. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33140. }
  33141. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33142. if (parsedMesh.localMatrix) {
  33143. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33144. }
  33145. else if (parsedMesh.pivotMatrix) {
  33146. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33147. }
  33148. mesh.setEnabled(parsedMesh.isEnabled);
  33149. mesh.isVisible = parsedMesh.isVisible;
  33150. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33151. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33152. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33153. if (parsedMesh.applyFog !== undefined) {
  33154. mesh.applyFog = parsedMesh.applyFog;
  33155. }
  33156. if (parsedMesh.pickable !== undefined) {
  33157. mesh.isPickable = parsedMesh.pickable;
  33158. }
  33159. if (parsedMesh.alphaIndex !== undefined) {
  33160. mesh.alphaIndex = parsedMesh.alphaIndex;
  33161. }
  33162. mesh.receiveShadows = parsedMesh.receiveShadows;
  33163. mesh.billboardMode = parsedMesh.billboardMode;
  33164. if (parsedMesh.visibility !== undefined) {
  33165. mesh.visibility = parsedMesh.visibility;
  33166. }
  33167. mesh.checkCollisions = parsedMesh.checkCollisions;
  33168. if (parsedMesh.isBlocker !== undefined) {
  33169. mesh.isBlocker = parsedMesh.isBlocker;
  33170. }
  33171. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33172. // freezeWorldMatrix
  33173. if (parsedMesh.freezeWorldMatrix) {
  33174. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33175. }
  33176. // Parent
  33177. if (parsedMesh.parentId) {
  33178. mesh._waitingParentId = parsedMesh.parentId;
  33179. }
  33180. // Actions
  33181. if (parsedMesh.actions !== undefined) {
  33182. mesh._waitingActions = parsedMesh.actions;
  33183. }
  33184. // Overlay
  33185. if (parsedMesh.overlayAlpha !== undefined) {
  33186. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33187. }
  33188. if (parsedMesh.overlayColor !== undefined) {
  33189. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33190. }
  33191. if (parsedMesh.renderOverlay !== undefined) {
  33192. mesh.renderOverlay = parsedMesh.renderOverlay;
  33193. }
  33194. // Geometry
  33195. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33196. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33197. if (parsedMesh.delayLoadingFile) {
  33198. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33199. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33200. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33201. if (parsedMesh._binaryInfo) {
  33202. mesh._binaryInfo = parsedMesh._binaryInfo;
  33203. }
  33204. mesh._delayInfo = [];
  33205. if (parsedMesh.hasUVs) {
  33206. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33207. }
  33208. if (parsedMesh.hasUVs2) {
  33209. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33210. }
  33211. if (parsedMesh.hasUVs3) {
  33212. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33213. }
  33214. if (parsedMesh.hasUVs4) {
  33215. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33216. }
  33217. if (parsedMesh.hasUVs5) {
  33218. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33219. }
  33220. if (parsedMesh.hasUVs6) {
  33221. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33222. }
  33223. if (parsedMesh.hasColors) {
  33224. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33225. }
  33226. if (parsedMesh.hasMatricesIndices) {
  33227. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33228. }
  33229. if (parsedMesh.hasMatricesWeights) {
  33230. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33231. }
  33232. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33233. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33234. mesh._checkDelayState();
  33235. }
  33236. }
  33237. else {
  33238. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33239. }
  33240. // Material
  33241. if (parsedMesh.materialId) {
  33242. mesh.setMaterialByID(parsedMesh.materialId);
  33243. }
  33244. else {
  33245. mesh.material = null;
  33246. }
  33247. // Morph targets
  33248. if (parsedMesh.morphTargetManagerId > -1) {
  33249. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33250. }
  33251. // Skeleton
  33252. if (parsedMesh.skeletonId > -1) {
  33253. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33254. if (parsedMesh.numBoneInfluencers) {
  33255. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33256. }
  33257. }
  33258. // Animations
  33259. if (parsedMesh.animations) {
  33260. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33261. var parsedAnimation = parsedMesh.animations[animationIndex];
  33262. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33263. }
  33264. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33265. }
  33266. if (parsedMesh.autoAnimate) {
  33267. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33268. }
  33269. // Layer Mask
  33270. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33271. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33272. }
  33273. else {
  33274. mesh.layerMask = 0x0FFFFFFF;
  33275. }
  33276. // Physics
  33277. if (parsedMesh.physicsImpostor) {
  33278. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33279. mass: parsedMesh.physicsMass,
  33280. friction: parsedMesh.physicsFriction,
  33281. restitution: parsedMesh.physicsRestitution
  33282. }, scene);
  33283. }
  33284. // Instances
  33285. if (parsedMesh.instances) {
  33286. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33287. var parsedInstance = parsedMesh.instances[index];
  33288. var instance = mesh.createInstance(parsedInstance.name);
  33289. if (parsedInstance.id) {
  33290. instance.id = parsedInstance.id;
  33291. }
  33292. if (BABYLON.Tags) {
  33293. if (parsedInstance.tags) {
  33294. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33295. }
  33296. else {
  33297. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33298. }
  33299. }
  33300. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33301. if (parsedInstance.parentId) {
  33302. instance._waitingParentId = parsedInstance.parentId;
  33303. }
  33304. if (parsedInstance.rotationQuaternion) {
  33305. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33306. }
  33307. else if (parsedInstance.rotation) {
  33308. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33309. }
  33310. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33311. instance.checkCollisions = mesh.checkCollisions;
  33312. if (parsedMesh.animations) {
  33313. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33314. parsedAnimation = parsedMesh.animations[animationIndex];
  33315. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33316. }
  33317. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33318. if (parsedMesh.autoAnimate) {
  33319. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33320. }
  33321. }
  33322. }
  33323. }
  33324. return mesh;
  33325. };
  33326. /**
  33327. * Creates a ribbon mesh.
  33328. * Please consider using the same method from the MeshBuilder class instead.
  33329. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33330. *
  33331. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33332. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33333. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33334. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33335. * 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.
  33336. * 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.
  33337. * 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
  33338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33339. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33341. */
  33342. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33343. if (closeArray === void 0) { closeArray = false; }
  33344. if (updatable === void 0) { updatable = false; }
  33345. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33346. pathArray: pathArray,
  33347. closeArray: closeArray,
  33348. closePath: closePath,
  33349. offset: offset,
  33350. updatable: updatable,
  33351. sideOrientation: sideOrientation,
  33352. instance: instance
  33353. }, scene);
  33354. };
  33355. /**
  33356. * Creates a plane polygonal mesh. By default, this is a disc.
  33357. * Please consider using the same method from the MeshBuilder class instead.
  33358. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33359. * 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.
  33360. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33361. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33363. */
  33364. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33365. if (scene === void 0) { scene = null; }
  33366. var options = {
  33367. radius: radius,
  33368. tessellation: tessellation,
  33369. sideOrientation: sideOrientation,
  33370. updatable: updatable
  33371. };
  33372. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33373. };
  33374. /**
  33375. * Creates a box mesh.
  33376. * Please consider using the same method from the MeshBuilder class instead.
  33377. * The parameter `size` sets the size (float) of each box side (default 1).
  33378. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33379. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33380. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33381. */
  33382. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33383. if (scene === void 0) { scene = null; }
  33384. var options = {
  33385. size: size,
  33386. sideOrientation: sideOrientation,
  33387. updatable: updatable
  33388. };
  33389. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33390. };
  33391. /**
  33392. * Creates a sphere mesh.
  33393. * Please consider using the same method from the MeshBuilder class instead.
  33394. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33395. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33397. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33398. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33399. */
  33400. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33401. var options = {
  33402. segments: segments,
  33403. diameterX: diameter,
  33404. diameterY: diameter,
  33405. diameterZ: diameter,
  33406. sideOrientation: sideOrientation,
  33407. updatable: updatable
  33408. };
  33409. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33410. };
  33411. /**
  33412. * Creates a cylinder or a cone mesh.
  33413. * Please consider using the same method from the MeshBuilder class instead.
  33414. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33415. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33416. * 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.
  33417. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33418. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33420. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33422. */
  33423. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33424. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33425. if (scene !== undefined) {
  33426. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33427. updatable = scene;
  33428. }
  33429. scene = subdivisions;
  33430. subdivisions = 1;
  33431. }
  33432. var options = {
  33433. height: height,
  33434. diameterTop: diameterTop,
  33435. diameterBottom: diameterBottom,
  33436. tessellation: tessellation,
  33437. subdivisions: subdivisions,
  33438. sideOrientation: sideOrientation,
  33439. updatable: updatable
  33440. };
  33441. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33442. };
  33443. // Torus (Code from SharpDX.org)
  33444. /**
  33445. * Creates a torus mesh.
  33446. * Please consider using the same method from the MeshBuilder class instead.
  33447. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33448. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33449. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33451. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33453. */
  33454. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33455. var options = {
  33456. diameter: diameter,
  33457. thickness: thickness,
  33458. tessellation: tessellation,
  33459. sideOrientation: sideOrientation,
  33460. updatable: updatable
  33461. };
  33462. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33463. };
  33464. /**
  33465. * Creates a torus knot mesh.
  33466. * Please consider using the same method from the MeshBuilder class instead.
  33467. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33468. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33469. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33470. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33472. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33474. */
  33475. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33476. var options = {
  33477. radius: radius,
  33478. tube: tube,
  33479. radialSegments: radialSegments,
  33480. tubularSegments: tubularSegments,
  33481. p: p,
  33482. q: q,
  33483. sideOrientation: sideOrientation,
  33484. updatable: updatable
  33485. };
  33486. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33487. };
  33488. /**
  33489. * Creates a line mesh.
  33490. * Please consider using the same method from the MeshBuilder class instead.
  33491. * 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.
  33492. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33493. * The parameter `points` is an array successive Vector3.
  33494. * 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
  33495. * When updating an instance, remember that only point positions can change, not the number of points.
  33496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33497. */
  33498. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33499. if (scene === void 0) { scene = null; }
  33500. if (updatable === void 0) { updatable = false; }
  33501. if (instance === void 0) { instance = null; }
  33502. var options = {
  33503. points: points,
  33504. updatable: updatable,
  33505. instance: instance
  33506. };
  33507. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33508. };
  33509. /**
  33510. * Creates a dashed line mesh.
  33511. * Please consider using the same method from the MeshBuilder class instead.
  33512. * 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.
  33513. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33514. * The parameter `points` is an array successive Vector3.
  33515. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33516. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33517. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33518. * 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
  33519. * When updating an instance, remember that only point positions can change, not the number of points.
  33520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33521. */
  33522. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33523. if (scene === void 0) { scene = null; }
  33524. var options = {
  33525. points: points,
  33526. dashSize: dashSize,
  33527. gapSize: gapSize,
  33528. dashNb: dashNb,
  33529. updatable: updatable,
  33530. instance: instance
  33531. };
  33532. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33533. };
  33534. /**
  33535. * Creates a polygon mesh.
  33536. * Please consider using the same method from the MeshBuilder class instead.
  33537. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33538. * 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.
  33539. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33541. * Remember you can only change the shape positions, not their number when updating a polygon.
  33542. */
  33543. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33544. var options = {
  33545. shape: shape,
  33546. holes: holes,
  33547. updatable: updatable,
  33548. sideOrientation: sideOrientation
  33549. };
  33550. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33551. };
  33552. /**
  33553. * Creates an extruded polygon mesh, with depth in the Y direction.
  33554. * Please consider using the same method from the MeshBuilder class instead.
  33555. */
  33556. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33557. var options = {
  33558. shape: shape,
  33559. holes: holes,
  33560. depth: depth,
  33561. updatable: updatable,
  33562. sideOrientation: sideOrientation
  33563. };
  33564. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33565. };
  33566. /**
  33567. * Creates an extruded shape mesh.
  33568. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33569. * Please consider using the same method from the MeshBuilder class instead.
  33570. *
  33571. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33572. * 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
  33573. * extruded along the Z axis.
  33574. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33575. * 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.
  33576. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33577. * 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
  33578. * 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
  33579. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33581. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33583. */
  33584. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33585. if (scene === void 0) { scene = null; }
  33586. var options = {
  33587. shape: shape,
  33588. path: path,
  33589. scale: scale,
  33590. rotation: rotation,
  33591. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33592. sideOrientation: sideOrientation,
  33593. instance: instance,
  33594. updatable: updatable
  33595. };
  33596. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33597. };
  33598. /**
  33599. * Creates an custom extruded shape mesh.
  33600. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33601. * Please consider using the same method from the MeshBuilder class instead.
  33602. *
  33603. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33604. * 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
  33605. * extruded along the Z axis.
  33606. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33607. * 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
  33608. * and the distance of this point from the begining of the path :
  33609. * ```javascript
  33610. * var rotationFunction = function(i, distance) {
  33611. * // do things
  33612. * return rotationValue; }
  33613. * ```
  33614. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33615. * 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
  33616. * and the distance of this point from the begining of the path :
  33617. * ```javascript
  33618. * var scaleFunction = function(i, distance) {
  33619. * // do things
  33620. * return scaleValue;}
  33621. * ```
  33622. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33623. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33624. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33625. * 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
  33626. * 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
  33627. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33629. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33631. */
  33632. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33633. var options = {
  33634. shape: shape,
  33635. path: path,
  33636. scaleFunction: scaleFunction,
  33637. rotationFunction: rotationFunction,
  33638. ribbonCloseArray: ribbonCloseArray,
  33639. ribbonClosePath: ribbonClosePath,
  33640. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33641. sideOrientation: sideOrientation,
  33642. instance: instance,
  33643. updatable: updatable
  33644. };
  33645. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33646. };
  33647. /**
  33648. * Creates lathe mesh.
  33649. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33650. * Please consider using the same method from the MeshBuilder class instead.
  33651. * 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
  33652. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33653. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33654. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33656. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33658. */
  33659. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33660. var options = {
  33661. shape: shape,
  33662. radius: radius,
  33663. tessellation: tessellation,
  33664. sideOrientation: sideOrientation,
  33665. updatable: updatable
  33666. };
  33667. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33668. };
  33669. /**
  33670. * Creates a plane mesh.
  33671. * Please consider using the same method from the MeshBuilder class instead.
  33672. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33673. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33674. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33676. */
  33677. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33678. var options = {
  33679. size: size,
  33680. width: size,
  33681. height: size,
  33682. sideOrientation: sideOrientation,
  33683. updatable: updatable
  33684. };
  33685. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33686. };
  33687. /**
  33688. * Creates a ground mesh.
  33689. * Please consider using the same method from the MeshBuilder class instead.
  33690. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33691. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33693. */
  33694. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33695. var options = {
  33696. width: width,
  33697. height: height,
  33698. subdivisions: subdivisions,
  33699. updatable: updatable
  33700. };
  33701. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33702. };
  33703. /**
  33704. * Creates a tiled ground mesh.
  33705. * Please consider using the same method from the MeshBuilder class instead.
  33706. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33707. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33708. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33709. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33710. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33711. * numbers of subdivisions on the ground width and height of each tile.
  33712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33713. */
  33714. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33715. var options = {
  33716. xmin: xmin,
  33717. zmin: zmin,
  33718. xmax: xmax,
  33719. zmax: zmax,
  33720. subdivisions: subdivisions,
  33721. precision: precision,
  33722. updatable: updatable
  33723. };
  33724. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33725. };
  33726. /**
  33727. * Creates a ground mesh from a height map.
  33728. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33729. * Please consider using the same method from the MeshBuilder class instead.
  33730. * The parameter `url` sets the URL of the height map image resource.
  33731. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33732. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33733. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33734. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33735. * 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).
  33736. * This function is passed the newly built mesh :
  33737. * ```javascript
  33738. * function(mesh) { // do things
  33739. * return; }
  33740. * ```
  33741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33742. */
  33743. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33744. var options = {
  33745. width: width,
  33746. height: height,
  33747. subdivisions: subdivisions,
  33748. minHeight: minHeight,
  33749. maxHeight: maxHeight,
  33750. updatable: updatable,
  33751. onReady: onReady
  33752. };
  33753. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33754. };
  33755. /**
  33756. * Creates a tube mesh.
  33757. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33758. * Please consider using the same method from the MeshBuilder class instead.
  33759. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33760. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33761. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33762. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33763. * 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.
  33764. * It must return a radius value (positive float) :
  33765. * ```javascript
  33766. * var radiusFunction = function(i, distance) {
  33767. * // do things
  33768. * return radius; }
  33769. * ```
  33770. * 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
  33771. * 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
  33772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33773. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33775. */
  33776. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33777. var options = {
  33778. path: path,
  33779. radius: radius,
  33780. tessellation: tessellation,
  33781. radiusFunction: radiusFunction,
  33782. arc: 1,
  33783. cap: cap,
  33784. updatable: updatable,
  33785. sideOrientation: sideOrientation,
  33786. instance: instance
  33787. };
  33788. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33789. };
  33790. /**
  33791. * Creates a polyhedron mesh.
  33792. * Please consider using the same method from the MeshBuilder class instead.
  33793. * 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
  33794. * to choose the wanted type.
  33795. * The parameter `size` (positive float, default 1) sets the polygon size.
  33796. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33797. * 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`.
  33798. * 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
  33799. * 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)`).
  33800. * 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
  33801. * 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.
  33802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33803. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33805. */
  33806. Mesh.CreatePolyhedron = function (name, options, scene) {
  33807. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33808. };
  33809. /**
  33810. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33811. * Please consider using the same method from the MeshBuilder class instead.
  33812. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33813. * 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`).
  33814. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33815. * 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.
  33816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33817. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33819. */
  33820. Mesh.CreateIcoSphere = function (name, options, scene) {
  33821. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33822. };
  33823. /**
  33824. * Creates a decal mesh.
  33825. * Please consider using the same method from the MeshBuilder class instead.
  33826. * 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.
  33827. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33828. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33829. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33830. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33831. */
  33832. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33833. var options = {
  33834. position: position,
  33835. normal: normal,
  33836. size: size,
  33837. angle: angle
  33838. };
  33839. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33840. };
  33841. // Skeletons
  33842. /**
  33843. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33844. */
  33845. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33846. if (!this._sourcePositions) {
  33847. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33848. if (!source) {
  33849. return this._sourcePositions;
  33850. }
  33851. this._sourcePositions = new Float32Array(source);
  33852. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33853. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33854. }
  33855. }
  33856. return this._sourcePositions;
  33857. };
  33858. /**
  33859. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33860. */
  33861. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33862. if (!this._sourceNormals) {
  33863. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33864. if (!source) {
  33865. return this._sourceNormals;
  33866. }
  33867. this._sourceNormals = new Float32Array(source);
  33868. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33869. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33870. }
  33871. }
  33872. return this._sourceNormals;
  33873. };
  33874. /**
  33875. * Updates the vertex buffer by applying transformation from the bones.
  33876. * Returns the Mesh.
  33877. *
  33878. * @param {skeleton} skeleton to apply
  33879. */
  33880. Mesh.prototype.applySkeleton = function (skeleton) {
  33881. if (!this.geometry) {
  33882. return this;
  33883. }
  33884. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33885. return this;
  33886. }
  33887. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33888. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33889. return this;
  33890. }
  33891. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33892. return this;
  33893. }
  33894. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33895. return this;
  33896. }
  33897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33898. return this;
  33899. }
  33900. if (!this._sourcePositions) {
  33901. var submeshes = this.subMeshes.slice();
  33902. this.setPositionsForCPUSkinning();
  33903. this.subMeshes = submeshes;
  33904. }
  33905. if (!this._sourceNormals) {
  33906. this.setNormalsForCPUSkinning();
  33907. }
  33908. // positionsData checks for not being Float32Array will only pass at most once
  33909. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33910. if (!positionsData) {
  33911. return this;
  33912. }
  33913. if (!(positionsData instanceof Float32Array)) {
  33914. positionsData = new Float32Array(positionsData);
  33915. }
  33916. // normalsData checks for not being Float32Array will only pass at most once
  33917. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33918. if (!normalsData) {
  33919. return this;
  33920. }
  33921. if (!(normalsData instanceof Float32Array)) {
  33922. normalsData = new Float32Array(normalsData);
  33923. }
  33924. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33925. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33926. if (!matricesWeightsData || !matricesIndicesData) {
  33927. return this;
  33928. }
  33929. var needExtras = this.numBoneInfluencers > 4;
  33930. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33931. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33932. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33933. var tempVector3 = BABYLON.Vector3.Zero();
  33934. var finalMatrix = new BABYLON.Matrix();
  33935. var tempMatrix = new BABYLON.Matrix();
  33936. var matWeightIdx = 0;
  33937. var inf;
  33938. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33939. var weight;
  33940. for (inf = 0; inf < 4; inf++) {
  33941. weight = matricesWeightsData[matWeightIdx + inf];
  33942. if (weight > 0) {
  33943. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33944. finalMatrix.addToSelf(tempMatrix);
  33945. }
  33946. }
  33947. if (needExtras) {
  33948. for (inf = 0; inf < 4; inf++) {
  33949. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33950. if (weight > 0) {
  33951. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33952. finalMatrix.addToSelf(tempMatrix);
  33953. }
  33954. }
  33955. }
  33956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33957. tempVector3.toArray(positionsData, index);
  33958. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33959. tempVector3.toArray(normalsData, index);
  33960. finalMatrix.reset();
  33961. }
  33962. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33963. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33964. return this;
  33965. };
  33966. // Tools
  33967. /**
  33968. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33969. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33970. */
  33971. Mesh.MinMax = function (meshes) {
  33972. var minVector = null;
  33973. var maxVector = null;
  33974. meshes.forEach(function (mesh, index, array) {
  33975. var boundingInfo = mesh.getBoundingInfo();
  33976. var boundingBox = boundingInfo.boundingBox;
  33977. if (!minVector || !maxVector) {
  33978. minVector = boundingBox.minimumWorld;
  33979. maxVector = boundingBox.maximumWorld;
  33980. }
  33981. else {
  33982. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33983. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33984. }
  33985. });
  33986. if (!minVector || !maxVector) {
  33987. return {
  33988. min: BABYLON.Vector3.Zero(),
  33989. max: BABYLON.Vector3.Zero()
  33990. };
  33991. }
  33992. return {
  33993. min: minVector,
  33994. max: maxVector
  33995. };
  33996. };
  33997. /**
  33998. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33999. */
  34000. Mesh.Center = function (meshesOrMinMaxVector) {
  34001. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34002. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34003. };
  34004. /**
  34005. * Merge the array of meshes into a single mesh for performance reasons.
  34006. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34007. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34008. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34009. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34010. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34011. */
  34012. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34013. if (disposeSource === void 0) { disposeSource = true; }
  34014. var index;
  34015. if (!allow32BitsIndices) {
  34016. var totalVertices = 0;
  34017. // Counting vertices
  34018. for (index = 0; index < meshes.length; index++) {
  34019. if (meshes[index]) {
  34020. totalVertices += meshes[index].getTotalVertices();
  34021. if (totalVertices > 65536) {
  34022. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34023. return null;
  34024. }
  34025. }
  34026. }
  34027. }
  34028. // Merge
  34029. var vertexData = null;
  34030. var otherVertexData;
  34031. var indiceArray = new Array();
  34032. var source = null;
  34033. for (index = 0; index < meshes.length; index++) {
  34034. if (meshes[index]) {
  34035. var wm = meshes[index].computeWorldMatrix(true);
  34036. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34037. otherVertexData.transform(wm);
  34038. if (vertexData) {
  34039. vertexData.merge(otherVertexData, allow32BitsIndices);
  34040. }
  34041. else {
  34042. vertexData = otherVertexData;
  34043. source = meshes[index];
  34044. }
  34045. if (subdivideWithSubMeshes) {
  34046. indiceArray.push(meshes[index].getTotalIndices());
  34047. }
  34048. }
  34049. }
  34050. source = source;
  34051. if (!meshSubclass) {
  34052. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34053. }
  34054. vertexData.applyToMesh(meshSubclass);
  34055. // Setting properties
  34056. meshSubclass.material = source.material;
  34057. meshSubclass.checkCollisions = source.checkCollisions;
  34058. // Cleaning
  34059. if (disposeSource) {
  34060. for (index = 0; index < meshes.length; index++) {
  34061. if (meshes[index]) {
  34062. meshes[index].dispose();
  34063. }
  34064. }
  34065. }
  34066. // Subdivide
  34067. if (subdivideWithSubMeshes) {
  34068. //-- removal of global submesh
  34069. meshSubclass.releaseSubMeshes();
  34070. index = 0;
  34071. var offset = 0;
  34072. //-- apply subdivision according to index table
  34073. while (index < indiceArray.length) {
  34074. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34075. offset += indiceArray[index];
  34076. index++;
  34077. }
  34078. }
  34079. return meshSubclass;
  34080. };
  34081. // Consts
  34082. Mesh._FRONTSIDE = 0;
  34083. Mesh._BACKSIDE = 1;
  34084. Mesh._DOUBLESIDE = 2;
  34085. Mesh._DEFAULTSIDE = 0;
  34086. Mesh._NO_CAP = 0;
  34087. Mesh._CAP_START = 1;
  34088. Mesh._CAP_END = 2;
  34089. Mesh._CAP_ALL = 3;
  34090. return Mesh;
  34091. }(BABYLON.AbstractMesh));
  34092. BABYLON.Mesh = Mesh;
  34093. })(BABYLON || (BABYLON = {}));
  34094. //# sourceMappingURL=babylon.mesh.js.map
  34095. var BABYLON;
  34096. (function (BABYLON) {
  34097. var BaseSubMesh = /** @class */ (function () {
  34098. function BaseSubMesh() {
  34099. }
  34100. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34101. get: function () {
  34102. return this._materialEffect;
  34103. },
  34104. enumerable: true,
  34105. configurable: true
  34106. });
  34107. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34108. if (defines === void 0) { defines = null; }
  34109. if (this._materialEffect === effect) {
  34110. if (!effect) {
  34111. this._materialDefines = null;
  34112. }
  34113. return;
  34114. }
  34115. this._materialDefines = defines;
  34116. this._materialEffect = effect;
  34117. };
  34118. return BaseSubMesh;
  34119. }());
  34120. BABYLON.BaseSubMesh = BaseSubMesh;
  34121. var SubMesh = /** @class */ (function (_super) {
  34122. __extends(SubMesh, _super);
  34123. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34124. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34125. var _this = _super.call(this) || this;
  34126. _this.materialIndex = materialIndex;
  34127. _this.verticesStart = verticesStart;
  34128. _this.verticesCount = verticesCount;
  34129. _this.indexStart = indexStart;
  34130. _this.indexCount = indexCount;
  34131. /** @hidden */
  34132. _this._renderId = 0;
  34133. _this._mesh = mesh;
  34134. _this._renderingMesh = renderingMesh || mesh;
  34135. mesh.subMeshes.push(_this);
  34136. _this._trianglePlanes = [];
  34137. _this._id = mesh.subMeshes.length - 1;
  34138. if (createBoundingBox) {
  34139. _this.refreshBoundingInfo();
  34140. mesh.computeWorldMatrix(true);
  34141. }
  34142. return _this;
  34143. }
  34144. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34145. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34146. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34147. };
  34148. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34149. get: function () {
  34150. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34151. },
  34152. enumerable: true,
  34153. configurable: true
  34154. });
  34155. /**
  34156. * Returns the submesh BoudingInfo object.
  34157. */
  34158. SubMesh.prototype.getBoundingInfo = function () {
  34159. if (this.IsGlobal) {
  34160. return this._mesh.getBoundingInfo();
  34161. }
  34162. return this._boundingInfo;
  34163. };
  34164. /**
  34165. * Sets the submesh BoundingInfo.
  34166. * Return the SubMesh.
  34167. */
  34168. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34169. this._boundingInfo = boundingInfo;
  34170. return this;
  34171. };
  34172. /**
  34173. * Returns the mesh of the current submesh.
  34174. */
  34175. SubMesh.prototype.getMesh = function () {
  34176. return this._mesh;
  34177. };
  34178. /**
  34179. * Returns the rendering mesh of the submesh.
  34180. */
  34181. SubMesh.prototype.getRenderingMesh = function () {
  34182. return this._renderingMesh;
  34183. };
  34184. /**
  34185. * Returns the submesh material.
  34186. */
  34187. SubMesh.prototype.getMaterial = function () {
  34188. var rootMaterial = this._renderingMesh.material;
  34189. if (rootMaterial === null || rootMaterial === undefined) {
  34190. return this._mesh.getScene().defaultMaterial;
  34191. }
  34192. else if (rootMaterial.getSubMaterial) {
  34193. var multiMaterial = rootMaterial;
  34194. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34195. if (this._currentMaterial !== effectiveMaterial) {
  34196. this._currentMaterial = effectiveMaterial;
  34197. this._materialDefines = null;
  34198. }
  34199. return effectiveMaterial;
  34200. }
  34201. return rootMaterial;
  34202. };
  34203. // Methods
  34204. /**
  34205. * Sets a new updated BoundingInfo object to the submesh.
  34206. * Returns the SubMesh.
  34207. */
  34208. SubMesh.prototype.refreshBoundingInfo = function () {
  34209. this._lastColliderWorldVertices = null;
  34210. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34211. return this;
  34212. }
  34213. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34214. if (!data) {
  34215. this._boundingInfo = this._mesh.getBoundingInfo();
  34216. return this;
  34217. }
  34218. var indices = this._renderingMesh.getIndices();
  34219. var extend;
  34220. //is this the only submesh?
  34221. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34222. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34223. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34224. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34225. }
  34226. else {
  34227. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34228. }
  34229. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34230. return this;
  34231. };
  34232. /** @hidden */
  34233. SubMesh.prototype._checkCollision = function (collider) {
  34234. var boundingInfo = this.getBoundingInfo();
  34235. return boundingInfo._checkCollision(collider);
  34236. };
  34237. /**
  34238. * Updates the submesh BoundingInfo.
  34239. * Returns the Submesh.
  34240. */
  34241. SubMesh.prototype.updateBoundingInfo = function (world) {
  34242. var boundingInfo = this.getBoundingInfo();
  34243. if (!boundingInfo) {
  34244. this.refreshBoundingInfo();
  34245. boundingInfo = this.getBoundingInfo();
  34246. }
  34247. boundingInfo.update(world);
  34248. return this;
  34249. };
  34250. /**
  34251. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34252. * Boolean returned.
  34253. */
  34254. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34255. var boundingInfo = this.getBoundingInfo();
  34256. if (!boundingInfo) {
  34257. return false;
  34258. }
  34259. return boundingInfo.isInFrustum(frustumPlanes);
  34260. };
  34261. /**
  34262. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34263. * Boolean returned.
  34264. */
  34265. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34266. var boundingInfo = this.getBoundingInfo();
  34267. if (!boundingInfo) {
  34268. return false;
  34269. }
  34270. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34271. };
  34272. /**
  34273. * Renders the submesh.
  34274. * Returns it.
  34275. */
  34276. SubMesh.prototype.render = function (enableAlphaMode) {
  34277. this._renderingMesh.render(this, enableAlphaMode);
  34278. return this;
  34279. };
  34280. /**
  34281. * Returns a new Index Buffer.
  34282. * Type returned : WebGLBuffer.
  34283. */
  34284. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34285. if (!this._linesIndexBuffer) {
  34286. var linesIndices = [];
  34287. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34288. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34289. }
  34290. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34291. this.linesIndexCount = linesIndices.length;
  34292. }
  34293. return this._linesIndexBuffer;
  34294. };
  34295. /**
  34296. * True is the passed Ray intersects the submesh bounding box.
  34297. * Boolean returned.
  34298. */
  34299. SubMesh.prototype.canIntersects = function (ray) {
  34300. var boundingInfo = this.getBoundingInfo();
  34301. if (!boundingInfo) {
  34302. return false;
  34303. }
  34304. return ray.intersectsBox(boundingInfo.boundingBox);
  34305. };
  34306. /**
  34307. * Returns an object IntersectionInfo.
  34308. */
  34309. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34310. var intersectInfo = null;
  34311. var material = this.getMaterial();
  34312. if (!material) {
  34313. return null;
  34314. }
  34315. switch (material.fillMode) {
  34316. case BABYLON.Material.PointListDrawMode:
  34317. case BABYLON.Material.LineListDrawMode:
  34318. case BABYLON.Material.LineLoopDrawMode:
  34319. case BABYLON.Material.LineStripDrawMode:
  34320. case BABYLON.Material.TriangleFanDrawMode:
  34321. case BABYLON.Material.TriangleStripDrawMode:
  34322. return null;
  34323. }
  34324. // LineMesh first as it's also a Mesh...
  34325. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34326. var lineMesh = this._mesh;
  34327. // Line test
  34328. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34329. var p0 = positions[indices[index]];
  34330. var p1 = positions[indices[index + 1]];
  34331. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34332. if (length < 0) {
  34333. continue;
  34334. }
  34335. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34336. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34337. if (fastCheck) {
  34338. break;
  34339. }
  34340. }
  34341. }
  34342. }
  34343. else {
  34344. // Triangles test
  34345. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34346. var p0 = positions[indices[index]];
  34347. var p1 = positions[indices[index + 1]];
  34348. var p2 = positions[indices[index + 2]];
  34349. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34350. if (currentIntersectInfo) {
  34351. if (currentIntersectInfo.distance < 0) {
  34352. continue;
  34353. }
  34354. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34355. intersectInfo = currentIntersectInfo;
  34356. intersectInfo.faceId = index / 3;
  34357. if (fastCheck) {
  34358. break;
  34359. }
  34360. }
  34361. }
  34362. }
  34363. }
  34364. return intersectInfo;
  34365. };
  34366. /** @hidden */
  34367. SubMesh.prototype._rebuild = function () {
  34368. if (this._linesIndexBuffer) {
  34369. this._linesIndexBuffer = null;
  34370. }
  34371. };
  34372. // Clone
  34373. /**
  34374. * Creates a new Submesh from the passed Mesh.
  34375. */
  34376. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34377. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34378. if (!this.IsGlobal) {
  34379. var boundingInfo = this.getBoundingInfo();
  34380. if (!boundingInfo) {
  34381. return result;
  34382. }
  34383. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34384. }
  34385. return result;
  34386. };
  34387. // Dispose
  34388. /**
  34389. * Disposes the Submesh.
  34390. * Returns nothing.
  34391. */
  34392. SubMesh.prototype.dispose = function () {
  34393. if (this._linesIndexBuffer) {
  34394. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34395. this._linesIndexBuffer = null;
  34396. }
  34397. // Remove from mesh
  34398. var index = this._mesh.subMeshes.indexOf(this);
  34399. this._mesh.subMeshes.splice(index, 1);
  34400. };
  34401. // Statics
  34402. /**
  34403. * Creates a new Submesh from the passed parameters :
  34404. * - materialIndex (integer) : the index of the main mesh material.
  34405. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34406. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34407. * - mesh (Mesh) : the main mesh to create the submesh from.
  34408. * - renderingMesh (optional Mesh) : rendering mesh.
  34409. */
  34410. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34411. var minVertexIndex = Number.MAX_VALUE;
  34412. var maxVertexIndex = -Number.MAX_VALUE;
  34413. renderingMesh = (renderingMesh || mesh);
  34414. var indices = renderingMesh.getIndices();
  34415. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34416. var vertexIndex = indices[index];
  34417. if (vertexIndex < minVertexIndex)
  34418. minVertexIndex = vertexIndex;
  34419. if (vertexIndex > maxVertexIndex)
  34420. maxVertexIndex = vertexIndex;
  34421. }
  34422. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34423. };
  34424. return SubMesh;
  34425. }(BaseSubMesh));
  34426. BABYLON.SubMesh = SubMesh;
  34427. })(BABYLON || (BABYLON = {}));
  34428. //# sourceMappingURL=babylon.subMesh.js.map
  34429. var __assign = (this && this.__assign) || function () {
  34430. __assign = Object.assign || function(t) {
  34431. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34432. s = arguments[i];
  34433. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34434. t[p] = s[p];
  34435. }
  34436. return t;
  34437. };
  34438. return __assign.apply(this, arguments);
  34439. };
  34440. var BABYLON;
  34441. (function (BABYLON) {
  34442. /**
  34443. * Manages the defines for the Material
  34444. */
  34445. var MaterialDefines = /** @class */ (function () {
  34446. function MaterialDefines() {
  34447. this._isDirty = true;
  34448. /** @hidden */
  34449. this._areLightsDirty = true;
  34450. /** @hidden */
  34451. this._areAttributesDirty = true;
  34452. /** @hidden */
  34453. this._areTexturesDirty = true;
  34454. /** @hidden */
  34455. this._areFresnelDirty = true;
  34456. /** @hidden */
  34457. this._areMiscDirty = true;
  34458. /** @hidden */
  34459. this._areImageProcessingDirty = true;
  34460. /** @hidden */
  34461. this._normals = false;
  34462. /** @hidden */
  34463. this._uvs = false;
  34464. /** @hidden */
  34465. this._needNormals = false;
  34466. /** @hidden */
  34467. this._needUVs = false;
  34468. }
  34469. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34470. /**
  34471. * Specifies if the material needs to be re-calculated
  34472. */
  34473. get: function () {
  34474. return this._isDirty;
  34475. },
  34476. enumerable: true,
  34477. configurable: true
  34478. });
  34479. /**
  34480. * Marks the material to indicate that it has been re-calculated
  34481. */
  34482. MaterialDefines.prototype.markAsProcessed = function () {
  34483. this._isDirty = false;
  34484. this._areAttributesDirty = false;
  34485. this._areTexturesDirty = false;
  34486. this._areFresnelDirty = false;
  34487. this._areLightsDirty = false;
  34488. this._areMiscDirty = false;
  34489. this._areImageProcessingDirty = false;
  34490. };
  34491. /**
  34492. * Marks the material to indicate that it needs to be re-calculated
  34493. */
  34494. MaterialDefines.prototype.markAsUnprocessed = function () {
  34495. this._isDirty = true;
  34496. };
  34497. /**
  34498. * Marks the material to indicate all of its defines need to be re-calculated
  34499. */
  34500. MaterialDefines.prototype.markAllAsDirty = function () {
  34501. this._areTexturesDirty = true;
  34502. this._areAttributesDirty = true;
  34503. this._areLightsDirty = true;
  34504. this._areFresnelDirty = true;
  34505. this._areMiscDirty = true;
  34506. this._areImageProcessingDirty = true;
  34507. this._isDirty = true;
  34508. };
  34509. /**
  34510. * Marks the material to indicate that image processing needs to be re-calculated
  34511. */
  34512. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34513. this._areImageProcessingDirty = true;
  34514. this._isDirty = true;
  34515. };
  34516. /**
  34517. * Marks the material to indicate the lights need to be re-calculated
  34518. */
  34519. MaterialDefines.prototype.markAsLightDirty = function () {
  34520. this._areLightsDirty = true;
  34521. this._isDirty = true;
  34522. };
  34523. /**
  34524. * Marks the attribute state as changed
  34525. */
  34526. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34527. this._areAttributesDirty = true;
  34528. this._isDirty = true;
  34529. };
  34530. /**
  34531. * Marks the texture state as changed
  34532. */
  34533. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34534. this._areTexturesDirty = true;
  34535. this._isDirty = true;
  34536. };
  34537. /**
  34538. * Marks the fresnel state as changed
  34539. */
  34540. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34541. this._areFresnelDirty = true;
  34542. this._isDirty = true;
  34543. };
  34544. /**
  34545. * Marks the misc state as changed
  34546. */
  34547. MaterialDefines.prototype.markAsMiscDirty = function () {
  34548. this._areMiscDirty = true;
  34549. this._isDirty = true;
  34550. };
  34551. /**
  34552. * Rebuilds the material defines
  34553. */
  34554. MaterialDefines.prototype.rebuild = function () {
  34555. if (this._keys) {
  34556. delete this._keys;
  34557. }
  34558. this._keys = [];
  34559. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34560. var key = _a[_i];
  34561. if (key[0] === "_") {
  34562. continue;
  34563. }
  34564. this._keys.push(key);
  34565. }
  34566. };
  34567. /**
  34568. * Specifies if two material defines are equal
  34569. * @param other - A material define instance to compare to
  34570. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34571. */
  34572. MaterialDefines.prototype.isEqual = function (other) {
  34573. if (this._keys.length !== other._keys.length) {
  34574. return false;
  34575. }
  34576. for (var index = 0; index < this._keys.length; index++) {
  34577. var prop = this._keys[index];
  34578. if (this[prop] !== other[prop]) {
  34579. return false;
  34580. }
  34581. }
  34582. return true;
  34583. };
  34584. /**
  34585. * Clones this instance's defines to another instance
  34586. * @param other - material defines to clone values to
  34587. */
  34588. MaterialDefines.prototype.cloneTo = function (other) {
  34589. if (this._keys.length !== other._keys.length) {
  34590. other._keys = this._keys.slice(0);
  34591. }
  34592. for (var index = 0; index < this._keys.length; index++) {
  34593. var prop = this._keys[index];
  34594. other[prop] = this[prop];
  34595. }
  34596. };
  34597. /**
  34598. * Resets the material define values
  34599. */
  34600. MaterialDefines.prototype.reset = function () {
  34601. for (var index = 0; index < this._keys.length; index++) {
  34602. var prop = this._keys[index];
  34603. var type = typeof this[prop];
  34604. switch (type) {
  34605. case "number":
  34606. this[prop] = 0;
  34607. break;
  34608. case "string":
  34609. this[prop] = "";
  34610. break;
  34611. default:
  34612. this[prop] = false;
  34613. break;
  34614. }
  34615. }
  34616. };
  34617. /**
  34618. * Converts the material define values to a string
  34619. * @returns - String of material define information
  34620. */
  34621. MaterialDefines.prototype.toString = function () {
  34622. var result = "";
  34623. for (var index = 0; index < this._keys.length; index++) {
  34624. var prop = this._keys[index];
  34625. var value = this[prop];
  34626. var type = typeof value;
  34627. switch (type) {
  34628. case "number":
  34629. case "string":
  34630. result += "#define " + prop + " " + value + "\n";
  34631. break;
  34632. default:
  34633. if (value) {
  34634. result += "#define " + prop + "\n";
  34635. }
  34636. break;
  34637. }
  34638. }
  34639. return result;
  34640. };
  34641. return MaterialDefines;
  34642. }());
  34643. BABYLON.MaterialDefines = MaterialDefines;
  34644. /**
  34645. * Base class for the main features of a material in Babylon.js
  34646. */
  34647. var Material = /** @class */ (function () {
  34648. /**
  34649. * Creates a material instance
  34650. * @param name defines the name of the material
  34651. * @param scene defines the scene to reference
  34652. * @param doNotAdd specifies if the material should be added to the scene
  34653. */
  34654. function Material(name, scene, doNotAdd) {
  34655. /**
  34656. * Specifies if the ready state should be checked on each call
  34657. */
  34658. this.checkReadyOnEveryCall = false;
  34659. /**
  34660. * Specifies if the ready state should be checked once
  34661. */
  34662. this.checkReadyOnlyOnce = false;
  34663. /**
  34664. * The state of the material
  34665. */
  34666. this.state = "";
  34667. /**
  34668. * The alpha value of the material
  34669. */
  34670. this._alpha = 1.0;
  34671. /**
  34672. * Specifies if back face culling is enabled
  34673. */
  34674. this._backFaceCulling = true;
  34675. /**
  34676. * Specifies if the material should be serialized
  34677. */
  34678. this.doNotSerialize = false;
  34679. /**
  34680. * Specifies if the effect should be stored on sub meshes
  34681. */
  34682. this.storeEffectOnSubMeshes = false;
  34683. /**
  34684. * An event triggered when the material is disposed
  34685. */
  34686. this.onDisposeObservable = new BABYLON.Observable();
  34687. /**
  34688. * Stores the value of the alpha mode
  34689. */
  34690. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34691. /**
  34692. * Stores the state of the need depth pre-pass value
  34693. */
  34694. this._needDepthPrePass = false;
  34695. /**
  34696. * Specifies if depth writing should be disabled
  34697. */
  34698. this.disableDepthWrite = false;
  34699. /**
  34700. * Specifies if depth writing should be forced
  34701. */
  34702. this.forceDepthWrite = false;
  34703. /**
  34704. * Specifies if there should be a separate pass for culling
  34705. */
  34706. this.separateCullingPass = false;
  34707. /**
  34708. * Stores the state specifing if fog should be enabled
  34709. */
  34710. this._fogEnabled = true;
  34711. /**
  34712. * Stores the size of points
  34713. */
  34714. this.pointSize = 1.0;
  34715. /**
  34716. * Stores the z offset value
  34717. */
  34718. this.zOffset = 0;
  34719. /**
  34720. * @hidden
  34721. * Specifies if the material was previously ready
  34722. */
  34723. this._wasPreviouslyReady = false;
  34724. /**
  34725. * Stores the fill mode state
  34726. */
  34727. this._fillMode = Material.TriangleFillMode;
  34728. this.name = name;
  34729. this.id = name || BABYLON.Tools.RandomId();
  34730. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34731. this.uniqueId = this._scene.getUniqueId();
  34732. if (this._scene.useRightHandedSystem) {
  34733. this.sideOrientation = Material.ClockWiseSideOrientation;
  34734. }
  34735. else {
  34736. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34737. }
  34738. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34739. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34740. if (!doNotAdd) {
  34741. this._scene.materials.push(this);
  34742. }
  34743. }
  34744. Object.defineProperty(Material, "TriangleFillMode", {
  34745. /**
  34746. * Returns the triangle fill mode
  34747. */
  34748. get: function () {
  34749. return Material._TriangleFillMode;
  34750. },
  34751. enumerable: true,
  34752. configurable: true
  34753. });
  34754. Object.defineProperty(Material, "WireFrameFillMode", {
  34755. /**
  34756. * Returns the wireframe mode
  34757. */
  34758. get: function () {
  34759. return Material._WireFrameFillMode;
  34760. },
  34761. enumerable: true,
  34762. configurable: true
  34763. });
  34764. Object.defineProperty(Material, "PointFillMode", {
  34765. /**
  34766. * Returns the point fill mode
  34767. */
  34768. get: function () {
  34769. return Material._PointFillMode;
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. Object.defineProperty(Material, "PointListDrawMode", {
  34775. /**
  34776. * Returns the point list draw mode
  34777. */
  34778. get: function () {
  34779. return Material._PointListDrawMode;
  34780. },
  34781. enumerable: true,
  34782. configurable: true
  34783. });
  34784. Object.defineProperty(Material, "LineListDrawMode", {
  34785. /**
  34786. * Returns the line list draw mode
  34787. */
  34788. get: function () {
  34789. return Material._LineListDrawMode;
  34790. },
  34791. enumerable: true,
  34792. configurable: true
  34793. });
  34794. Object.defineProperty(Material, "LineLoopDrawMode", {
  34795. /**
  34796. * Returns the line loop draw mode
  34797. */
  34798. get: function () {
  34799. return Material._LineLoopDrawMode;
  34800. },
  34801. enumerable: true,
  34802. configurable: true
  34803. });
  34804. Object.defineProperty(Material, "LineStripDrawMode", {
  34805. /**
  34806. * Returns the line strip draw mode
  34807. */
  34808. get: function () {
  34809. return Material._LineStripDrawMode;
  34810. },
  34811. enumerable: true,
  34812. configurable: true
  34813. });
  34814. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34815. /**
  34816. * Returns the triangle strip draw mode
  34817. */
  34818. get: function () {
  34819. return Material._TriangleStripDrawMode;
  34820. },
  34821. enumerable: true,
  34822. configurable: true
  34823. });
  34824. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34825. /**
  34826. * Returns the triangle fan draw mode
  34827. */
  34828. get: function () {
  34829. return Material._TriangleFanDrawMode;
  34830. },
  34831. enumerable: true,
  34832. configurable: true
  34833. });
  34834. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34835. /**
  34836. * Returns the clock-wise side orientation
  34837. */
  34838. get: function () {
  34839. return Material._ClockWiseSideOrientation;
  34840. },
  34841. enumerable: true,
  34842. configurable: true
  34843. });
  34844. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34845. /**
  34846. * Returns the counter clock-wise side orientation
  34847. */
  34848. get: function () {
  34849. return Material._CounterClockWiseSideOrientation;
  34850. },
  34851. enumerable: true,
  34852. configurable: true
  34853. });
  34854. Object.defineProperty(Material, "TextureDirtyFlag", {
  34855. /**
  34856. * Returns the dirty texture flag value
  34857. */
  34858. get: function () {
  34859. return Material._TextureDirtyFlag;
  34860. },
  34861. enumerable: true,
  34862. configurable: true
  34863. });
  34864. Object.defineProperty(Material, "LightDirtyFlag", {
  34865. /**
  34866. * Returns the dirty light flag value
  34867. */
  34868. get: function () {
  34869. return Material._LightDirtyFlag;
  34870. },
  34871. enumerable: true,
  34872. configurable: true
  34873. });
  34874. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34875. /**
  34876. * Returns the dirty fresnel flag value
  34877. */
  34878. get: function () {
  34879. return Material._FresnelDirtyFlag;
  34880. },
  34881. enumerable: true,
  34882. configurable: true
  34883. });
  34884. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34885. /**
  34886. * Returns the dirty attributes flag value
  34887. */
  34888. get: function () {
  34889. return Material._AttributesDirtyFlag;
  34890. },
  34891. enumerable: true,
  34892. configurable: true
  34893. });
  34894. Object.defineProperty(Material, "MiscDirtyFlag", {
  34895. /**
  34896. * Returns the dirty misc flag value
  34897. */
  34898. get: function () {
  34899. return Material._MiscDirtyFlag;
  34900. },
  34901. enumerable: true,
  34902. configurable: true
  34903. });
  34904. Object.defineProperty(Material.prototype, "alpha", {
  34905. /**
  34906. * Gets the alpha value of the material
  34907. */
  34908. get: function () {
  34909. return this._alpha;
  34910. },
  34911. /**
  34912. * Sets the alpha value of the material
  34913. */
  34914. set: function (value) {
  34915. if (this._alpha === value) {
  34916. return;
  34917. }
  34918. this._alpha = value;
  34919. this.markAsDirty(Material.MiscDirtyFlag);
  34920. },
  34921. enumerable: true,
  34922. configurable: true
  34923. });
  34924. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34925. /**
  34926. * Gets the back-face culling state
  34927. */
  34928. get: function () {
  34929. return this._backFaceCulling;
  34930. },
  34931. /**
  34932. * Sets the back-face culling state
  34933. */
  34934. set: function (value) {
  34935. if (this._backFaceCulling === value) {
  34936. return;
  34937. }
  34938. this._backFaceCulling = value;
  34939. this.markAsDirty(Material.TextureDirtyFlag);
  34940. },
  34941. enumerable: true,
  34942. configurable: true
  34943. });
  34944. Object.defineProperty(Material.prototype, "onDispose", {
  34945. /**
  34946. * Called during a dispose event
  34947. */
  34948. set: function (callback) {
  34949. if (this._onDisposeObserver) {
  34950. this.onDisposeObservable.remove(this._onDisposeObserver);
  34951. }
  34952. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(Material.prototype, "onBindObservable", {
  34958. /**
  34959. * An event triggered when the material is bound
  34960. */
  34961. get: function () {
  34962. if (!this._onBindObservable) {
  34963. this._onBindObservable = new BABYLON.Observable();
  34964. }
  34965. return this._onBindObservable;
  34966. },
  34967. enumerable: true,
  34968. configurable: true
  34969. });
  34970. Object.defineProperty(Material.prototype, "onBind", {
  34971. /**
  34972. * Called during a bind event
  34973. */
  34974. set: function (callback) {
  34975. if (this._onBindObserver) {
  34976. this.onBindObservable.remove(this._onBindObserver);
  34977. }
  34978. this._onBindObserver = this.onBindObservable.add(callback);
  34979. },
  34980. enumerable: true,
  34981. configurable: true
  34982. });
  34983. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34984. /**
  34985. * An event triggered when the material is unbound
  34986. */
  34987. get: function () {
  34988. if (!this._onUnBindObservable) {
  34989. this._onUnBindObservable = new BABYLON.Observable();
  34990. }
  34991. return this._onUnBindObservable;
  34992. },
  34993. enumerable: true,
  34994. configurable: true
  34995. });
  34996. Object.defineProperty(Material.prototype, "alphaMode", {
  34997. /**
  34998. * Gets the value of the alpha mode
  34999. */
  35000. get: function () {
  35001. return this._alphaMode;
  35002. },
  35003. /**
  35004. * Sets the value of the alpha mode.
  35005. *
  35006. * | Value | Type | Description |
  35007. * | --- | --- | --- |
  35008. * | 0 | ALPHA_DISABLE | |
  35009. * | 1 | ALPHA_ADD | |
  35010. * | 2 | ALPHA_COMBINE | |
  35011. * | 3 | ALPHA_SUBTRACT | |
  35012. * | 4 | ALPHA_MULTIPLY | |
  35013. * | 5 | ALPHA_MAXIMIZED | |
  35014. * | 6 | ALPHA_ONEONE | |
  35015. * | 7 | ALPHA_PREMULTIPLIED | |
  35016. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35017. * | 9 | ALPHA_INTERPOLATE | |
  35018. * | 10 | ALPHA_SCREENMODE | |
  35019. *
  35020. */
  35021. set: function (value) {
  35022. if (this._alphaMode === value) {
  35023. return;
  35024. }
  35025. this._alphaMode = value;
  35026. this.markAsDirty(Material.TextureDirtyFlag);
  35027. },
  35028. enumerable: true,
  35029. configurable: true
  35030. });
  35031. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35032. /**
  35033. * Gets the depth pre-pass value
  35034. */
  35035. get: function () {
  35036. return this._needDepthPrePass;
  35037. },
  35038. /**
  35039. * Sets the need depth pre-pass value
  35040. */
  35041. set: function (value) {
  35042. if (this._needDepthPrePass === value) {
  35043. return;
  35044. }
  35045. this._needDepthPrePass = value;
  35046. if (this._needDepthPrePass) {
  35047. this.checkReadyOnEveryCall = true;
  35048. }
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. Object.defineProperty(Material.prototype, "fogEnabled", {
  35054. /**
  35055. * Gets the value of the fog enabled state
  35056. */
  35057. get: function () {
  35058. return this._fogEnabled;
  35059. },
  35060. /**
  35061. * Sets the state for enabling fog
  35062. */
  35063. set: function (value) {
  35064. if (this._fogEnabled === value) {
  35065. return;
  35066. }
  35067. this._fogEnabled = value;
  35068. this.markAsDirty(Material.MiscDirtyFlag);
  35069. },
  35070. enumerable: true,
  35071. configurable: true
  35072. });
  35073. Object.defineProperty(Material.prototype, "wireframe", {
  35074. /**
  35075. * Gets a value specifying if wireframe mode is enabled
  35076. */
  35077. get: function () {
  35078. switch (this._fillMode) {
  35079. case Material.WireFrameFillMode:
  35080. case Material.LineListDrawMode:
  35081. case Material.LineLoopDrawMode:
  35082. case Material.LineStripDrawMode:
  35083. return true;
  35084. }
  35085. return this._scene.forceWireframe;
  35086. },
  35087. /**
  35088. * Sets the state of wireframe mode
  35089. */
  35090. set: function (value) {
  35091. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(Material.prototype, "pointsCloud", {
  35097. /**
  35098. * Gets the value specifying if point clouds are enabled
  35099. */
  35100. get: function () {
  35101. switch (this._fillMode) {
  35102. case Material.PointFillMode:
  35103. case Material.PointListDrawMode:
  35104. return true;
  35105. }
  35106. return this._scene.forcePointsCloud;
  35107. },
  35108. /**
  35109. * Sets the state of point cloud mode
  35110. */
  35111. set: function (value) {
  35112. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35113. },
  35114. enumerable: true,
  35115. configurable: true
  35116. });
  35117. Object.defineProperty(Material.prototype, "fillMode", {
  35118. /**
  35119. * Gets the material fill mode
  35120. */
  35121. get: function () {
  35122. return this._fillMode;
  35123. },
  35124. /**
  35125. * Sets the material fill mode
  35126. */
  35127. set: function (value) {
  35128. if (this._fillMode === value) {
  35129. return;
  35130. }
  35131. this._fillMode = value;
  35132. this.markAsDirty(Material.MiscDirtyFlag);
  35133. },
  35134. enumerable: true,
  35135. configurable: true
  35136. });
  35137. /**
  35138. * Returns a string representation of the current material
  35139. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35140. * @returns a string with material information
  35141. */
  35142. Material.prototype.toString = function (fullDetails) {
  35143. var ret = "Name: " + this.name;
  35144. if (fullDetails) {
  35145. }
  35146. return ret;
  35147. };
  35148. /**
  35149. * Gets the class name of the material
  35150. * @returns a string with the class name of the material
  35151. */
  35152. Material.prototype.getClassName = function () {
  35153. return "Material";
  35154. };
  35155. Object.defineProperty(Material.prototype, "isFrozen", {
  35156. /**
  35157. * Specifies if updates for the material been locked
  35158. */
  35159. get: function () {
  35160. return this.checkReadyOnlyOnce;
  35161. },
  35162. enumerable: true,
  35163. configurable: true
  35164. });
  35165. /**
  35166. * Locks updates for the material
  35167. */
  35168. Material.prototype.freeze = function () {
  35169. this.checkReadyOnlyOnce = true;
  35170. };
  35171. /**
  35172. * Unlocks updates for the material
  35173. */
  35174. Material.prototype.unfreeze = function () {
  35175. this.checkReadyOnlyOnce = false;
  35176. };
  35177. /**
  35178. * Specifies if the material is ready to be used
  35179. * @param mesh defines the mesh to check
  35180. * @param useInstances specifies if instances should be used
  35181. * @returns a boolean indicating if the material is ready to be used
  35182. */
  35183. Material.prototype.isReady = function (mesh, useInstances) {
  35184. return true;
  35185. };
  35186. /**
  35187. * Specifies that the submesh is ready to be used
  35188. * @param mesh defines the mesh to check
  35189. * @param subMesh defines which submesh to check
  35190. * @param useInstances specifies that instances should be used
  35191. * @returns a boolean indicating that the submesh is ready or not
  35192. */
  35193. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35194. return false;
  35195. };
  35196. /**
  35197. * Returns the material effect
  35198. * @returns the effect associated with the material
  35199. */
  35200. Material.prototype.getEffect = function () {
  35201. return this._effect;
  35202. };
  35203. /**
  35204. * Returns the current scene
  35205. * @returns a Scene
  35206. */
  35207. Material.prototype.getScene = function () {
  35208. return this._scene;
  35209. };
  35210. /**
  35211. * Specifies if the material will require alpha blending
  35212. * @returns a boolean specifying if alpha blending is needed
  35213. */
  35214. Material.prototype.needAlphaBlending = function () {
  35215. return (this.alpha < 1.0);
  35216. };
  35217. /**
  35218. * Specifies if the mesh will require alpha blending
  35219. * @param mesh defines the mesh to check
  35220. * @returns a boolean specifying if alpha blending is needed for the mesh
  35221. */
  35222. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35223. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35224. };
  35225. /**
  35226. * Specifies if this material should be rendered in alpha test mode
  35227. * @returns a boolean specifying if an alpha test is needed.
  35228. */
  35229. Material.prototype.needAlphaTesting = function () {
  35230. return false;
  35231. };
  35232. /**
  35233. * Gets the texture used for the alpha test
  35234. * @returns the texture to use for alpha testing
  35235. */
  35236. Material.prototype.getAlphaTestTexture = function () {
  35237. return null;
  35238. };
  35239. /**
  35240. * Marks the material to indicate that it needs to be re-calculated
  35241. */
  35242. Material.prototype.markDirty = function () {
  35243. this._wasPreviouslyReady = false;
  35244. };
  35245. /** @hidden */
  35246. Material.prototype._preBind = function (effect, overrideOrientation) {
  35247. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35248. var engine = this._scene.getEngine();
  35249. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35250. var reverse = orientation === Material.ClockWiseSideOrientation;
  35251. engine.enableEffect(effect ? effect : this._effect);
  35252. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35253. return reverse;
  35254. };
  35255. /**
  35256. * Binds the material to the mesh
  35257. * @param world defines the world transformation matrix
  35258. * @param mesh defines the mesh to bind the material to
  35259. */
  35260. Material.prototype.bind = function (world, mesh) {
  35261. };
  35262. /**
  35263. * Binds the submesh to the material
  35264. * @param world defines the world transformation matrix
  35265. * @param mesh defines the mesh containing the submesh
  35266. * @param subMesh defines the submesh to bind the material to
  35267. */
  35268. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35269. };
  35270. /**
  35271. * Binds the world matrix to the material
  35272. * @param world defines the world transformation matrix
  35273. */
  35274. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35275. };
  35276. /**
  35277. * Binds the scene's uniform buffer to the effect.
  35278. * @param effect defines the effect to bind to the scene uniform buffer
  35279. * @param sceneUbo defines the uniform buffer storing scene data
  35280. */
  35281. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35282. sceneUbo.bindToEffect(effect, "Scene");
  35283. };
  35284. /**
  35285. * Binds the view matrix to the effect
  35286. * @param effect defines the effect to bind the view matrix to
  35287. */
  35288. Material.prototype.bindView = function (effect) {
  35289. if (!this._useUBO) {
  35290. effect.setMatrix("view", this.getScene().getViewMatrix());
  35291. }
  35292. else {
  35293. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35294. }
  35295. };
  35296. /**
  35297. * Binds the view projection matrix to the effect
  35298. * @param effect defines the effect to bind the view projection matrix to
  35299. */
  35300. Material.prototype.bindViewProjection = function (effect) {
  35301. if (!this._useUBO) {
  35302. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35303. }
  35304. else {
  35305. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35306. }
  35307. };
  35308. /**
  35309. * Specifies if material alpha testing should be turned on for the mesh
  35310. * @param mesh defines the mesh to check
  35311. */
  35312. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35313. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35314. };
  35315. /**
  35316. * Processes to execute after binding the material to a mesh
  35317. * @param mesh defines the rendered mesh
  35318. */
  35319. Material.prototype._afterBind = function (mesh) {
  35320. this._scene._cachedMaterial = this;
  35321. if (mesh) {
  35322. this._scene._cachedVisibility = mesh.visibility;
  35323. }
  35324. else {
  35325. this._scene._cachedVisibility = 1;
  35326. }
  35327. if (this._onBindObservable && mesh) {
  35328. this._onBindObservable.notifyObservers(mesh);
  35329. }
  35330. if (this.disableDepthWrite) {
  35331. var engine = this._scene.getEngine();
  35332. this._cachedDepthWriteState = engine.getDepthWrite();
  35333. engine.setDepthWrite(false);
  35334. }
  35335. };
  35336. /**
  35337. * Unbinds the material from the mesh
  35338. */
  35339. Material.prototype.unbind = function () {
  35340. if (this._onUnBindObservable) {
  35341. this._onUnBindObservable.notifyObservers(this);
  35342. }
  35343. if (this.disableDepthWrite) {
  35344. var engine = this._scene.getEngine();
  35345. engine.setDepthWrite(this._cachedDepthWriteState);
  35346. }
  35347. };
  35348. /**
  35349. * Gets the active textures from the material
  35350. * @returns an array of textures
  35351. */
  35352. Material.prototype.getActiveTextures = function () {
  35353. return [];
  35354. };
  35355. /**
  35356. * Specifies if the material uses a texture
  35357. * @param texture defines the texture to check against the material
  35358. * @returns a boolean specifying if the material uses the texture
  35359. */
  35360. Material.prototype.hasTexture = function (texture) {
  35361. return false;
  35362. };
  35363. /**
  35364. * Makes a duplicate of the material, and gives it a new name
  35365. * @param name defines the new name for the duplicated material
  35366. * @returns the cloned material
  35367. */
  35368. Material.prototype.clone = function (name) {
  35369. return null;
  35370. };
  35371. /**
  35372. * Gets the meshes bound to the material
  35373. * @returns an array of meshes bound to the material
  35374. */
  35375. Material.prototype.getBindedMeshes = function () {
  35376. var result = new Array();
  35377. for (var index = 0; index < this._scene.meshes.length; index++) {
  35378. var mesh = this._scene.meshes[index];
  35379. if (mesh.material === this) {
  35380. result.push(mesh);
  35381. }
  35382. }
  35383. return result;
  35384. };
  35385. /**
  35386. * Force shader compilation
  35387. * @param mesh defines the mesh associated with this material
  35388. * @param onCompiled defines a function to execute once the material is compiled
  35389. * @param options defines the options to configure the compilation
  35390. */
  35391. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35392. var _this = this;
  35393. var localOptions = __assign({ clipPlane: false }, options);
  35394. var subMesh = new BABYLON.BaseSubMesh();
  35395. var scene = this.getScene();
  35396. var checkReady = function () {
  35397. if (!_this._scene || !_this._scene.getEngine()) {
  35398. return;
  35399. }
  35400. if (subMesh._materialDefines) {
  35401. subMesh._materialDefines._renderId = -1;
  35402. }
  35403. var clipPlaneState = scene.clipPlane;
  35404. if (localOptions.clipPlane) {
  35405. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35406. }
  35407. if (_this.storeEffectOnSubMeshes) {
  35408. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35409. if (onCompiled) {
  35410. onCompiled(_this);
  35411. }
  35412. }
  35413. else {
  35414. setTimeout(checkReady, 16);
  35415. }
  35416. }
  35417. else {
  35418. if (_this.isReady(mesh)) {
  35419. if (onCompiled) {
  35420. onCompiled(_this);
  35421. }
  35422. }
  35423. else {
  35424. setTimeout(checkReady, 16);
  35425. }
  35426. }
  35427. if (localOptions.clipPlane) {
  35428. scene.clipPlane = clipPlaneState;
  35429. }
  35430. };
  35431. checkReady();
  35432. };
  35433. /**
  35434. * Force shader compilation
  35435. * @param mesh defines the mesh that will use this material
  35436. * @param options defines additional options for compiling the shaders
  35437. * @returns a promise that resolves when the compilation completes
  35438. */
  35439. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35440. var _this = this;
  35441. return new Promise(function (resolve) {
  35442. _this.forceCompilation(mesh, function () {
  35443. resolve();
  35444. }, options);
  35445. });
  35446. };
  35447. /**
  35448. * Marks a define in the material to indicate that it needs to be re-computed
  35449. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35450. */
  35451. Material.prototype.markAsDirty = function (flag) {
  35452. if (flag & Material.TextureDirtyFlag) {
  35453. this._markAllSubMeshesAsTexturesDirty();
  35454. }
  35455. if (flag & Material.LightDirtyFlag) {
  35456. this._markAllSubMeshesAsLightsDirty();
  35457. }
  35458. if (flag & Material.FresnelDirtyFlag) {
  35459. this._markAllSubMeshesAsFresnelDirty();
  35460. }
  35461. if (flag & Material.AttributesDirtyFlag) {
  35462. this._markAllSubMeshesAsAttributesDirty();
  35463. }
  35464. if (flag & Material.MiscDirtyFlag) {
  35465. this._markAllSubMeshesAsMiscDirty();
  35466. }
  35467. this.getScene().resetCachedMaterial();
  35468. };
  35469. /**
  35470. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35471. * @param func defines a function which checks material defines against the submeshes
  35472. */
  35473. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35474. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35475. var mesh = _a[_i];
  35476. if (!mesh.subMeshes) {
  35477. continue;
  35478. }
  35479. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35480. var subMesh = _c[_b];
  35481. if (subMesh.getMaterial() !== this) {
  35482. continue;
  35483. }
  35484. if (!subMesh._materialDefines) {
  35485. continue;
  35486. }
  35487. func(subMesh._materialDefines);
  35488. }
  35489. }
  35490. };
  35491. /**
  35492. * Indicates that image processing needs to be re-calculated for all submeshes
  35493. */
  35494. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35495. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35496. };
  35497. /**
  35498. * Indicates that textures need to be re-calculated for all submeshes
  35499. */
  35500. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35501. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35502. };
  35503. /**
  35504. * Indicates that fresnel needs to be re-calculated for all submeshes
  35505. */
  35506. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35507. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35508. };
  35509. /**
  35510. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35511. */
  35512. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35513. this._markAllSubMeshesAsDirty(function (defines) {
  35514. defines.markAsFresnelDirty();
  35515. defines.markAsMiscDirty();
  35516. });
  35517. };
  35518. /**
  35519. * Indicates that lights need to be re-calculated for all submeshes
  35520. */
  35521. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35522. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35523. };
  35524. /**
  35525. * Indicates that attributes need to be re-calculated for all submeshes
  35526. */
  35527. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35528. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35529. };
  35530. /**
  35531. * Indicates that misc needs to be re-calculated for all submeshes
  35532. */
  35533. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35534. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35535. };
  35536. /**
  35537. * Indicates that textures and misc need to be re-calculated for all submeshes
  35538. */
  35539. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35540. this._markAllSubMeshesAsDirty(function (defines) {
  35541. defines.markAsTexturesDirty();
  35542. defines.markAsMiscDirty();
  35543. });
  35544. };
  35545. /**
  35546. * Disposes the material
  35547. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35548. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35549. */
  35550. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35551. // Animations
  35552. this.getScene().stopAnimation(this);
  35553. this.getScene().freeProcessedMaterials();
  35554. // Remove from scene
  35555. var index = this._scene.materials.indexOf(this);
  35556. if (index >= 0) {
  35557. this._scene.materials.splice(index, 1);
  35558. }
  35559. // Remove from meshes
  35560. for (index = 0; index < this._scene.meshes.length; index++) {
  35561. var mesh = this._scene.meshes[index];
  35562. if (mesh.material === this) {
  35563. mesh.material = null;
  35564. if (mesh.geometry) {
  35565. var geometry = (mesh.geometry);
  35566. if (this.storeEffectOnSubMeshes) {
  35567. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35568. var subMesh = _a[_i];
  35569. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35570. if (forceDisposeEffect && subMesh._materialEffect) {
  35571. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35572. }
  35573. }
  35574. }
  35575. else {
  35576. geometry._releaseVertexArrayObject(this._effect);
  35577. }
  35578. }
  35579. }
  35580. }
  35581. this._uniformBuffer.dispose();
  35582. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35583. if (forceDisposeEffect && this._effect) {
  35584. if (!this.storeEffectOnSubMeshes) {
  35585. this._scene.getEngine()._releaseEffect(this._effect);
  35586. }
  35587. this._effect = null;
  35588. }
  35589. // Callback
  35590. this.onDisposeObservable.notifyObservers(this);
  35591. this.onDisposeObservable.clear();
  35592. if (this._onBindObservable) {
  35593. this._onBindObservable.clear();
  35594. }
  35595. if (this._onUnBindObservable) {
  35596. this._onUnBindObservable.clear();
  35597. }
  35598. };
  35599. /**
  35600. * Serializes this material
  35601. * @returns the serialized material object
  35602. */
  35603. Material.prototype.serialize = function () {
  35604. return BABYLON.SerializationHelper.Serialize(this);
  35605. };
  35606. /**
  35607. * Creates a MultiMaterial from parsed MultiMaterial data.
  35608. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35609. * @param scene defines the hosting scene
  35610. * @returns a new MultiMaterial
  35611. */
  35612. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35613. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35614. multiMaterial.id = parsedMultiMaterial.id;
  35615. if (BABYLON.Tags) {
  35616. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35617. }
  35618. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35619. var subMatId = parsedMultiMaterial.materials[matIndex];
  35620. if (subMatId) {
  35621. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35622. }
  35623. else {
  35624. multiMaterial.subMaterials.push(null);
  35625. }
  35626. }
  35627. return multiMaterial;
  35628. };
  35629. /**
  35630. * Creates a material from parsed material data
  35631. * @param parsedMaterial defines parsed material data
  35632. * @param scene defines the hosting scene
  35633. * @param rootUrl defines the root URL to use to load textures
  35634. * @returns a new material
  35635. */
  35636. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35637. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35638. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35639. }
  35640. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35641. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35642. if (!BABYLON.LegacyPBRMaterial) {
  35643. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35644. return;
  35645. }
  35646. }
  35647. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35648. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35649. };
  35650. // Triangle views
  35651. Material._TriangleFillMode = 0;
  35652. Material._WireFrameFillMode = 1;
  35653. Material._PointFillMode = 2;
  35654. // Draw modes
  35655. Material._PointListDrawMode = 3;
  35656. Material._LineListDrawMode = 4;
  35657. Material._LineLoopDrawMode = 5;
  35658. Material._LineStripDrawMode = 6;
  35659. Material._TriangleStripDrawMode = 7;
  35660. Material._TriangleFanDrawMode = 8;
  35661. /**
  35662. * Stores the clock-wise side orientation
  35663. */
  35664. Material._ClockWiseSideOrientation = 0;
  35665. /**
  35666. * Stores the counter clock-wise side orientation
  35667. */
  35668. Material._CounterClockWiseSideOrientation = 1;
  35669. /**
  35670. * The dirty texture flag value
  35671. */
  35672. Material._TextureDirtyFlag = 1;
  35673. /**
  35674. * The dirty light flag value
  35675. */
  35676. Material._LightDirtyFlag = 2;
  35677. /**
  35678. * The dirty fresnel flag value
  35679. */
  35680. Material._FresnelDirtyFlag = 4;
  35681. /**
  35682. * The dirty attribute flag value
  35683. */
  35684. Material._AttributesDirtyFlag = 8;
  35685. /**
  35686. * The dirty misc flag value
  35687. */
  35688. Material._MiscDirtyFlag = 16;
  35689. __decorate([
  35690. BABYLON.serialize()
  35691. ], Material.prototype, "id", void 0);
  35692. __decorate([
  35693. BABYLON.serialize()
  35694. ], Material.prototype, "uniqueId", void 0);
  35695. __decorate([
  35696. BABYLON.serialize()
  35697. ], Material.prototype, "name", void 0);
  35698. __decorate([
  35699. BABYLON.serialize()
  35700. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35701. __decorate([
  35702. BABYLON.serialize()
  35703. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35704. __decorate([
  35705. BABYLON.serialize()
  35706. ], Material.prototype, "state", void 0);
  35707. __decorate([
  35708. BABYLON.serialize("alpha")
  35709. ], Material.prototype, "_alpha", void 0);
  35710. __decorate([
  35711. BABYLON.serialize("backFaceCulling")
  35712. ], Material.prototype, "_backFaceCulling", void 0);
  35713. __decorate([
  35714. BABYLON.serialize()
  35715. ], Material.prototype, "sideOrientation", void 0);
  35716. __decorate([
  35717. BABYLON.serialize("alphaMode")
  35718. ], Material.prototype, "_alphaMode", void 0);
  35719. __decorate([
  35720. BABYLON.serialize()
  35721. ], Material.prototype, "_needDepthPrePass", void 0);
  35722. __decorate([
  35723. BABYLON.serialize()
  35724. ], Material.prototype, "disableDepthWrite", void 0);
  35725. __decorate([
  35726. BABYLON.serialize()
  35727. ], Material.prototype, "forceDepthWrite", void 0);
  35728. __decorate([
  35729. BABYLON.serialize()
  35730. ], Material.prototype, "separateCullingPass", void 0);
  35731. __decorate([
  35732. BABYLON.serialize("fogEnabled")
  35733. ], Material.prototype, "_fogEnabled", void 0);
  35734. __decorate([
  35735. BABYLON.serialize()
  35736. ], Material.prototype, "pointSize", void 0);
  35737. __decorate([
  35738. BABYLON.serialize()
  35739. ], Material.prototype, "zOffset", void 0);
  35740. __decorate([
  35741. BABYLON.serialize()
  35742. ], Material.prototype, "wireframe", null);
  35743. __decorate([
  35744. BABYLON.serialize()
  35745. ], Material.prototype, "pointsCloud", null);
  35746. __decorate([
  35747. BABYLON.serialize()
  35748. ], Material.prototype, "fillMode", null);
  35749. return Material;
  35750. }());
  35751. BABYLON.Material = Material;
  35752. })(BABYLON || (BABYLON = {}));
  35753. //# sourceMappingURL=babylon.material.js.map
  35754. var BABYLON;
  35755. (function (BABYLON) {
  35756. var UniformBuffer = /** @class */ (function () {
  35757. /**
  35758. * Uniform buffer objects.
  35759. *
  35760. * Handles blocks of uniform on the GPU.
  35761. *
  35762. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35763. *
  35764. * For more information, please refer to :
  35765. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35766. */
  35767. function UniformBuffer(engine, data, dynamic) {
  35768. this._engine = engine;
  35769. this._noUBO = !engine.supportsUniformBuffers;
  35770. this._dynamic = dynamic;
  35771. this._data = data || [];
  35772. this._uniformLocations = {};
  35773. this._uniformSizes = {};
  35774. this._uniformLocationPointer = 0;
  35775. this._needSync = false;
  35776. if (this._noUBO) {
  35777. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35778. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35779. this.updateFloat = this._updateFloatForEffect;
  35780. this.updateFloat2 = this._updateFloat2ForEffect;
  35781. this.updateFloat3 = this._updateFloat3ForEffect;
  35782. this.updateFloat4 = this._updateFloat4ForEffect;
  35783. this.updateMatrix = this._updateMatrixForEffect;
  35784. this.updateVector3 = this._updateVector3ForEffect;
  35785. this.updateVector4 = this._updateVector4ForEffect;
  35786. this.updateColor3 = this._updateColor3ForEffect;
  35787. this.updateColor4 = this._updateColor4ForEffect;
  35788. }
  35789. else {
  35790. this._engine._uniformBuffers.push(this);
  35791. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35792. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35793. this.updateFloat = this._updateFloatForUniform;
  35794. this.updateFloat2 = this._updateFloat2ForUniform;
  35795. this.updateFloat3 = this._updateFloat3ForUniform;
  35796. this.updateFloat4 = this._updateFloat4ForUniform;
  35797. this.updateMatrix = this._updateMatrixForUniform;
  35798. this.updateVector3 = this._updateVector3ForUniform;
  35799. this.updateVector4 = this._updateVector4ForUniform;
  35800. this.updateColor3 = this._updateColor3ForUniform;
  35801. this.updateColor4 = this._updateColor4ForUniform;
  35802. }
  35803. }
  35804. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35805. // Properties
  35806. /**
  35807. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35808. * or just falling back on setUniformXXX calls.
  35809. */
  35810. get: function () {
  35811. return !this._noUBO;
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35817. /**
  35818. * Indicates if the WebGL underlying uniform buffer is in sync
  35819. * with the javascript cache data.
  35820. */
  35821. get: function () {
  35822. return !this._needSync;
  35823. },
  35824. enumerable: true,
  35825. configurable: true
  35826. });
  35827. /**
  35828. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35829. * Also, a dynamic UniformBuffer will disable cache verification and always
  35830. * update the underlying WebGL uniform buffer to the GPU.
  35831. */
  35832. UniformBuffer.prototype.isDynamic = function () {
  35833. return this._dynamic !== undefined;
  35834. };
  35835. /**
  35836. * The data cache on JS side.
  35837. */
  35838. UniformBuffer.prototype.getData = function () {
  35839. return this._bufferData;
  35840. };
  35841. /**
  35842. * The underlying WebGL Uniform buffer.
  35843. */
  35844. UniformBuffer.prototype.getBuffer = function () {
  35845. return this._buffer;
  35846. };
  35847. /**
  35848. * std140 layout specifies how to align data within an UBO structure.
  35849. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35850. * for specs.
  35851. */
  35852. UniformBuffer.prototype._fillAlignment = function (size) {
  35853. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35854. // and 4x4 matrices
  35855. // TODO : change if other types are used
  35856. var alignment;
  35857. if (size <= 2) {
  35858. alignment = size;
  35859. }
  35860. else {
  35861. alignment = 4;
  35862. }
  35863. if ((this._uniformLocationPointer % alignment) !== 0) {
  35864. var oldPointer = this._uniformLocationPointer;
  35865. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35866. var diff = this._uniformLocationPointer - oldPointer;
  35867. for (var i = 0; i < diff; i++) {
  35868. this._data.push(0);
  35869. }
  35870. }
  35871. };
  35872. /**
  35873. * Adds an uniform in the buffer.
  35874. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35875. * for the layout to be correct !
  35876. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35877. * @param {number|number[]} size Data size, or data directly.
  35878. */
  35879. UniformBuffer.prototype.addUniform = function (name, size) {
  35880. if (this._noUBO) {
  35881. return;
  35882. }
  35883. if (this._uniformLocations[name] !== undefined) {
  35884. // Already existing uniform
  35885. return;
  35886. }
  35887. // This function must be called in the order of the shader layout !
  35888. // size can be the size of the uniform, or data directly
  35889. var data;
  35890. if (size instanceof Array) {
  35891. data = size;
  35892. size = data.length;
  35893. }
  35894. else {
  35895. size = size;
  35896. data = [];
  35897. // Fill with zeros
  35898. for (var i = 0; i < size; i++) {
  35899. data.push(0);
  35900. }
  35901. }
  35902. this._fillAlignment(size);
  35903. this._uniformSizes[name] = size;
  35904. this._uniformLocations[name] = this._uniformLocationPointer;
  35905. this._uniformLocationPointer += size;
  35906. for (var i = 0; i < size; i++) {
  35907. this._data.push(data[i]);
  35908. }
  35909. this._needSync = true;
  35910. };
  35911. /**
  35912. * Wrapper for addUniform.
  35913. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35914. * @param {Matrix} mat A 4x4 matrix.
  35915. */
  35916. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35917. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35918. };
  35919. /**
  35920. * Wrapper for addUniform.
  35921. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35922. * @param {number} x
  35923. * @param {number} y
  35924. */
  35925. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35926. var temp = [x, y];
  35927. this.addUniform(name, temp);
  35928. };
  35929. /**
  35930. * Wrapper for addUniform.
  35931. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35932. * @param {number} x
  35933. * @param {number} y
  35934. * @param {number} z
  35935. */
  35936. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35937. var temp = [x, y, z];
  35938. this.addUniform(name, temp);
  35939. };
  35940. /**
  35941. * Wrapper for addUniform.
  35942. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35943. * @param {Color3} color
  35944. */
  35945. UniformBuffer.prototype.addColor3 = function (name, color) {
  35946. var temp = new Array();
  35947. color.toArray(temp);
  35948. this.addUniform(name, temp);
  35949. };
  35950. /**
  35951. * Wrapper for addUniform.
  35952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35953. * @param {Color3} color
  35954. * @param {number} alpha
  35955. */
  35956. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35957. var temp = new Array();
  35958. color.toArray(temp);
  35959. temp.push(alpha);
  35960. this.addUniform(name, temp);
  35961. };
  35962. /**
  35963. * Wrapper for addUniform.
  35964. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35965. * @param {Vector3} vector
  35966. */
  35967. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35968. var temp = new Array();
  35969. vector.toArray(temp);
  35970. this.addUniform(name, temp);
  35971. };
  35972. /**
  35973. * Wrapper for addUniform.
  35974. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35975. */
  35976. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35977. this.addUniform(name, 12);
  35978. };
  35979. /**
  35980. * Wrapper for addUniform.
  35981. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35982. */
  35983. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35984. this.addUniform(name, 8);
  35985. };
  35986. /**
  35987. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35988. */
  35989. UniformBuffer.prototype.create = function () {
  35990. if (this._noUBO) {
  35991. return;
  35992. }
  35993. if (this._buffer) {
  35994. return; // nothing to do
  35995. }
  35996. // See spec, alignment must be filled as a vec4
  35997. this._fillAlignment(4);
  35998. this._bufferData = new Float32Array(this._data);
  35999. this._rebuild();
  36000. this._needSync = true;
  36001. };
  36002. /** @hidden */
  36003. UniformBuffer.prototype._rebuild = function () {
  36004. if (this._noUBO) {
  36005. return;
  36006. }
  36007. if (this._dynamic) {
  36008. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36009. }
  36010. else {
  36011. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36012. }
  36013. };
  36014. /**
  36015. * Updates the WebGL Uniform Buffer on the GPU.
  36016. * If the `dynamic` flag is set to true, no cache comparison is done.
  36017. * Otherwise, the buffer will be updated only if the cache differs.
  36018. */
  36019. UniformBuffer.prototype.update = function () {
  36020. if (!this._buffer) {
  36021. this.create();
  36022. return;
  36023. }
  36024. if (!this._dynamic && !this._needSync) {
  36025. return;
  36026. }
  36027. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36028. this._needSync = false;
  36029. };
  36030. /**
  36031. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36032. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36033. * @param {number[]|Float32Array} data Flattened data
  36034. * @param {number} size Size of the data.
  36035. */
  36036. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36037. var location = this._uniformLocations[uniformName];
  36038. if (location === undefined) {
  36039. if (this._buffer) {
  36040. // Cannot add an uniform if the buffer is already created
  36041. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36042. return;
  36043. }
  36044. this.addUniform(uniformName, size);
  36045. location = this._uniformLocations[uniformName];
  36046. }
  36047. if (!this._buffer) {
  36048. this.create();
  36049. }
  36050. if (!this._dynamic) {
  36051. // Cache for static uniform buffers
  36052. var changed = false;
  36053. for (var i = 0; i < size; i++) {
  36054. if (this._bufferData[location + i] !== data[i]) {
  36055. changed = true;
  36056. this._bufferData[location + i] = data[i];
  36057. }
  36058. }
  36059. this._needSync = this._needSync || changed;
  36060. }
  36061. else {
  36062. // No cache for dynamic
  36063. for (var i = 0; i < size; i++) {
  36064. this._bufferData[location + i] = data[i];
  36065. }
  36066. }
  36067. };
  36068. // Update methods
  36069. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36070. // To match std140, matrix must be realigned
  36071. for (var i = 0; i < 3; i++) {
  36072. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36073. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36074. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36075. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36076. }
  36077. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36078. };
  36079. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36080. this._currentEffect.setMatrix3x3(name, matrix);
  36081. };
  36082. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36083. this._currentEffect.setMatrix2x2(name, matrix);
  36084. };
  36085. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36086. // To match std140, matrix must be realigned
  36087. for (var i = 0; i < 2; i++) {
  36088. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36089. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36090. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36091. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36092. }
  36093. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36094. };
  36095. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36096. this._currentEffect.setFloat(name, x);
  36097. };
  36098. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36099. UniformBuffer._tempBuffer[0] = x;
  36100. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36101. };
  36102. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36103. if (suffix === void 0) { suffix = ""; }
  36104. this._currentEffect.setFloat2(name + suffix, x, y);
  36105. };
  36106. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36107. if (suffix === void 0) { suffix = ""; }
  36108. UniformBuffer._tempBuffer[0] = x;
  36109. UniformBuffer._tempBuffer[1] = y;
  36110. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36111. };
  36112. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36113. if (suffix === void 0) { suffix = ""; }
  36114. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36115. };
  36116. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36117. if (suffix === void 0) { suffix = ""; }
  36118. UniformBuffer._tempBuffer[0] = x;
  36119. UniformBuffer._tempBuffer[1] = y;
  36120. UniformBuffer._tempBuffer[2] = z;
  36121. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36122. };
  36123. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36124. if (suffix === void 0) { suffix = ""; }
  36125. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36126. };
  36127. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36128. if (suffix === void 0) { suffix = ""; }
  36129. UniformBuffer._tempBuffer[0] = x;
  36130. UniformBuffer._tempBuffer[1] = y;
  36131. UniformBuffer._tempBuffer[2] = z;
  36132. UniformBuffer._tempBuffer[3] = w;
  36133. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36134. };
  36135. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36136. this._currentEffect.setMatrix(name, mat);
  36137. };
  36138. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36139. this.updateUniform(name, mat.toArray(), 16);
  36140. };
  36141. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36142. this._currentEffect.setVector3(name, vector);
  36143. };
  36144. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36145. vector.toArray(UniformBuffer._tempBuffer);
  36146. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36147. };
  36148. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36149. this._currentEffect.setVector4(name, vector);
  36150. };
  36151. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36152. vector.toArray(UniformBuffer._tempBuffer);
  36153. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36154. };
  36155. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36156. if (suffix === void 0) { suffix = ""; }
  36157. this._currentEffect.setColor3(name + suffix, color);
  36158. };
  36159. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36160. if (suffix === void 0) { suffix = ""; }
  36161. color.toArray(UniformBuffer._tempBuffer);
  36162. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36163. };
  36164. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36165. if (suffix === void 0) { suffix = ""; }
  36166. this._currentEffect.setColor4(name + suffix, color, alpha);
  36167. };
  36168. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36169. if (suffix === void 0) { suffix = ""; }
  36170. color.toArray(UniformBuffer._tempBuffer);
  36171. UniformBuffer._tempBuffer[3] = alpha;
  36172. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36173. };
  36174. /**
  36175. * Sets a sampler uniform on the effect.
  36176. * @param {string} name Name of the sampler.
  36177. * @param {Texture} texture
  36178. */
  36179. UniformBuffer.prototype.setTexture = function (name, texture) {
  36180. this._currentEffect.setTexture(name, texture);
  36181. };
  36182. /**
  36183. * Directly updates the value of the uniform in the cache AND on the GPU.
  36184. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36185. * @param {number[]|Float32Array} data Flattened data
  36186. */
  36187. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36188. this.updateUniform(uniformName, data, data.length);
  36189. this.update();
  36190. };
  36191. /**
  36192. * Binds this uniform buffer to an effect.
  36193. * @param {Effect} effect
  36194. * @param {string} name Name of the uniform block in the shader.
  36195. */
  36196. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36197. this._currentEffect = effect;
  36198. if (this._noUBO || !this._buffer) {
  36199. return;
  36200. }
  36201. effect.bindUniformBuffer(this._buffer, name);
  36202. };
  36203. /**
  36204. * Disposes the uniform buffer.
  36205. */
  36206. UniformBuffer.prototype.dispose = function () {
  36207. if (this._noUBO) {
  36208. return;
  36209. }
  36210. var index = this._engine._uniformBuffers.indexOf(this);
  36211. if (index !== -1) {
  36212. this._engine._uniformBuffers.splice(index, 1);
  36213. }
  36214. if (!this._buffer) {
  36215. return;
  36216. }
  36217. if (this._engine._releaseBuffer(this._buffer)) {
  36218. this._buffer = null;
  36219. }
  36220. };
  36221. // Pool for avoiding memory leaks
  36222. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36223. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36224. return UniformBuffer;
  36225. }());
  36226. BABYLON.UniformBuffer = UniformBuffer;
  36227. })(BABYLON || (BABYLON = {}));
  36228. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36229. var BABYLON;
  36230. (function (BABYLON) {
  36231. /**
  36232. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36233. */
  36234. var VertexData = /** @class */ (function () {
  36235. function VertexData() {
  36236. }
  36237. /**
  36238. * Uses the passed data array to set the set the values for the specified kind of data
  36239. * @param data a linear array of floating numbers
  36240. * @param kind the type of data that is being set, eg positions, colors etc
  36241. */
  36242. VertexData.prototype.set = function (data, kind) {
  36243. switch (kind) {
  36244. case BABYLON.VertexBuffer.PositionKind:
  36245. this.positions = data;
  36246. break;
  36247. case BABYLON.VertexBuffer.NormalKind:
  36248. this.normals = data;
  36249. break;
  36250. case BABYLON.VertexBuffer.TangentKind:
  36251. this.tangents = data;
  36252. break;
  36253. case BABYLON.VertexBuffer.UVKind:
  36254. this.uvs = data;
  36255. break;
  36256. case BABYLON.VertexBuffer.UV2Kind:
  36257. this.uvs2 = data;
  36258. break;
  36259. case BABYLON.VertexBuffer.UV3Kind:
  36260. this.uvs3 = data;
  36261. break;
  36262. case BABYLON.VertexBuffer.UV4Kind:
  36263. this.uvs4 = data;
  36264. break;
  36265. case BABYLON.VertexBuffer.UV5Kind:
  36266. this.uvs5 = data;
  36267. break;
  36268. case BABYLON.VertexBuffer.UV6Kind:
  36269. this.uvs6 = data;
  36270. break;
  36271. case BABYLON.VertexBuffer.ColorKind:
  36272. this.colors = data;
  36273. break;
  36274. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36275. this.matricesIndices = data;
  36276. break;
  36277. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36278. this.matricesWeights = data;
  36279. break;
  36280. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36281. this.matricesIndicesExtra = data;
  36282. break;
  36283. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36284. this.matricesWeightsExtra = data;
  36285. break;
  36286. }
  36287. };
  36288. /**
  36289. * Associates the vertexData to the passed Mesh.
  36290. * Sets it as updatable or not (default `false`)
  36291. * @param mesh the mesh the vertexData is applied to
  36292. * @param updatable when used and having the value true allows new data to update the vertexData
  36293. * @returns the VertexData
  36294. */
  36295. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36296. this._applyTo(mesh, updatable);
  36297. return this;
  36298. };
  36299. /**
  36300. * Associates the vertexData to the passed Geometry.
  36301. * Sets it as updatable or not (default `false`)
  36302. * @param geometry the geometry the vertexData is applied to
  36303. * @param updatable when used and having the value true allows new data to update the vertexData
  36304. * @returns VertexData
  36305. */
  36306. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36307. this._applyTo(geometry, updatable);
  36308. return this;
  36309. };
  36310. /**
  36311. * Updates the associated mesh
  36312. * @param mesh the mesh to be updated
  36313. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36314. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36315. * @returns VertexData
  36316. */
  36317. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36318. this._update(mesh);
  36319. return this;
  36320. };
  36321. /**
  36322. * Updates the associated geometry
  36323. * @param geometry the geometry to be updated
  36324. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36325. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36326. * @returns VertexData.
  36327. */
  36328. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36329. this._update(geometry);
  36330. return this;
  36331. };
  36332. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36333. if (updatable === void 0) { updatable = false; }
  36334. if (this.positions) {
  36335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36336. }
  36337. if (this.normals) {
  36338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36339. }
  36340. if (this.tangents) {
  36341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36342. }
  36343. if (this.uvs) {
  36344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36345. }
  36346. if (this.uvs2) {
  36347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36348. }
  36349. if (this.uvs3) {
  36350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36351. }
  36352. if (this.uvs4) {
  36353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36354. }
  36355. if (this.uvs5) {
  36356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36357. }
  36358. if (this.uvs6) {
  36359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36360. }
  36361. if (this.colors) {
  36362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36363. }
  36364. if (this.matricesIndices) {
  36365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36366. }
  36367. if (this.matricesWeights) {
  36368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36369. }
  36370. if (this.matricesIndicesExtra) {
  36371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36372. }
  36373. if (this.matricesWeightsExtra) {
  36374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36375. }
  36376. if (this.indices) {
  36377. meshOrGeometry.setIndices(this.indices, null, updatable);
  36378. }
  36379. else {
  36380. meshOrGeometry.setIndices([], null);
  36381. }
  36382. return this;
  36383. };
  36384. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36385. if (this.positions) {
  36386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36387. }
  36388. if (this.normals) {
  36389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36390. }
  36391. if (this.tangents) {
  36392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36393. }
  36394. if (this.uvs) {
  36395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36396. }
  36397. if (this.uvs2) {
  36398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36399. }
  36400. if (this.uvs3) {
  36401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36402. }
  36403. if (this.uvs4) {
  36404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36405. }
  36406. if (this.uvs5) {
  36407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36408. }
  36409. if (this.uvs6) {
  36410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36411. }
  36412. if (this.colors) {
  36413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36414. }
  36415. if (this.matricesIndices) {
  36416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36417. }
  36418. if (this.matricesWeights) {
  36419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36420. }
  36421. if (this.matricesIndicesExtra) {
  36422. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36423. }
  36424. if (this.matricesWeightsExtra) {
  36425. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36426. }
  36427. if (this.indices) {
  36428. meshOrGeometry.setIndices(this.indices, null);
  36429. }
  36430. return this;
  36431. };
  36432. /**
  36433. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36434. * @param matrix the transforming matrix
  36435. * @returns the VertexData
  36436. */
  36437. VertexData.prototype.transform = function (matrix) {
  36438. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36439. var transformed = BABYLON.Vector3.Zero();
  36440. var index;
  36441. if (this.positions) {
  36442. var position = BABYLON.Vector3.Zero();
  36443. for (index = 0; index < this.positions.length; index += 3) {
  36444. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36445. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36446. this.positions[index] = transformed.x;
  36447. this.positions[index + 1] = transformed.y;
  36448. this.positions[index + 2] = transformed.z;
  36449. }
  36450. }
  36451. if (this.normals) {
  36452. var normal = BABYLON.Vector3.Zero();
  36453. for (index = 0; index < this.normals.length; index += 3) {
  36454. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36455. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36456. this.normals[index] = transformed.x;
  36457. this.normals[index + 1] = transformed.y;
  36458. this.normals[index + 2] = transformed.z;
  36459. }
  36460. }
  36461. if (this.tangents) {
  36462. var tangent = BABYLON.Vector4.Zero();
  36463. var tangentTransformed = BABYLON.Vector4.Zero();
  36464. for (index = 0; index < this.tangents.length; index += 4) {
  36465. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36466. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36467. this.tangents[index] = tangentTransformed.x;
  36468. this.tangents[index + 1] = tangentTransformed.y;
  36469. this.tangents[index + 2] = tangentTransformed.z;
  36470. this.tangents[index + 3] = tangentTransformed.w;
  36471. }
  36472. }
  36473. if (flip && this.indices) {
  36474. for (index = 0; index < this.indices.length; index += 3) {
  36475. var tmp = this.indices[index + 1];
  36476. this.indices[index + 1] = this.indices[index + 2];
  36477. this.indices[index + 2] = tmp;
  36478. }
  36479. }
  36480. return this;
  36481. };
  36482. /**
  36483. * Merges the passed VertexData into the current one
  36484. * @param other the VertexData to be merged into the current one
  36485. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36486. * @returns the modified VertexData
  36487. */
  36488. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36489. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36490. this._validate();
  36491. other._validate();
  36492. if (!this.normals !== !other.normals ||
  36493. !this.tangents !== !other.tangents ||
  36494. !this.uvs !== !other.uvs ||
  36495. !this.uvs2 !== !other.uvs2 ||
  36496. !this.uvs3 !== !other.uvs3 ||
  36497. !this.uvs4 !== !other.uvs4 ||
  36498. !this.uvs5 !== !other.uvs5 ||
  36499. !this.uvs6 !== !other.uvs6 ||
  36500. !this.colors !== !other.colors ||
  36501. !this.matricesIndices !== !other.matricesIndices ||
  36502. !this.matricesWeights !== !other.matricesWeights ||
  36503. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36504. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36505. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36506. }
  36507. if (other.indices) {
  36508. if (!this.indices) {
  36509. this.indices = [];
  36510. }
  36511. var offset = this.positions ? this.positions.length / 3 : 0;
  36512. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36513. if (isSrcTypedArray) {
  36514. var len = this.indices.length + other.indices.length;
  36515. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36516. temp.set(this.indices);
  36517. var decal = this.indices.length;
  36518. for (var index = 0; index < other.indices.length; index++) {
  36519. temp[decal + index] = other.indices[index] + offset;
  36520. }
  36521. this.indices = temp;
  36522. }
  36523. else {
  36524. for (var index = 0; index < other.indices.length; index++) {
  36525. this.indices.push(other.indices[index] + offset);
  36526. }
  36527. }
  36528. }
  36529. this.positions = this._mergeElement(this.positions, other.positions);
  36530. this.normals = this._mergeElement(this.normals, other.normals);
  36531. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36532. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36533. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36534. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36535. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36536. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36537. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36538. this.colors = this._mergeElement(this.colors, other.colors);
  36539. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36540. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36541. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36542. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36543. return this;
  36544. };
  36545. VertexData.prototype._mergeElement = function (source, other) {
  36546. if (!source) {
  36547. return other;
  36548. }
  36549. if (!other) {
  36550. return source;
  36551. }
  36552. var len = other.length + source.length;
  36553. var isSrcTypedArray = source instanceof Float32Array;
  36554. var isOthTypedArray = other instanceof Float32Array;
  36555. // use non-loop method when the source is Float32Array
  36556. if (isSrcTypedArray) {
  36557. var ret32 = new Float32Array(len);
  36558. ret32.set(source);
  36559. ret32.set(other, source.length);
  36560. return ret32;
  36561. // source is number[], when other is also use concat
  36562. }
  36563. else if (!isOthTypedArray) {
  36564. return source.concat(other);
  36565. // source is a number[], but other is a Float32Array, loop required
  36566. }
  36567. else {
  36568. var ret = source.slice(0); // copy source to a separate array
  36569. for (var i = 0, len = other.length; i < len; i++) {
  36570. ret.push(other[i]);
  36571. }
  36572. return ret;
  36573. }
  36574. };
  36575. VertexData.prototype._validate = function () {
  36576. if (!this.positions) {
  36577. throw new Error("Positions are required");
  36578. }
  36579. var getElementCount = function (kind, values) {
  36580. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36581. if ((values.length % stride) !== 0) {
  36582. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36583. }
  36584. return values.length / stride;
  36585. };
  36586. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36587. var validateElementCount = function (kind, values) {
  36588. var elementCount = getElementCount(kind, values);
  36589. if (elementCount !== positionsElementCount) {
  36590. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36591. }
  36592. };
  36593. if (this.normals)
  36594. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36595. if (this.tangents)
  36596. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36597. if (this.uvs)
  36598. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36599. if (this.uvs2)
  36600. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36601. if (this.uvs3)
  36602. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36603. if (this.uvs4)
  36604. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36605. if (this.uvs5)
  36606. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36607. if (this.uvs6)
  36608. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36609. if (this.colors)
  36610. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36611. if (this.matricesIndices)
  36612. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36613. if (this.matricesWeights)
  36614. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36615. if (this.matricesIndicesExtra)
  36616. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36617. if (this.matricesWeightsExtra)
  36618. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36619. };
  36620. /**
  36621. * Serializes the VertexData
  36622. * @returns a serialized object
  36623. */
  36624. VertexData.prototype.serialize = function () {
  36625. var serializationObject = this.serialize();
  36626. if (this.positions) {
  36627. serializationObject.positions = this.positions;
  36628. }
  36629. if (this.normals) {
  36630. serializationObject.normals = this.normals;
  36631. }
  36632. if (this.tangents) {
  36633. serializationObject.tangents = this.tangents;
  36634. }
  36635. if (this.uvs) {
  36636. serializationObject.uvs = this.uvs;
  36637. }
  36638. if (this.uvs2) {
  36639. serializationObject.uvs2 = this.uvs2;
  36640. }
  36641. if (this.uvs3) {
  36642. serializationObject.uvs3 = this.uvs3;
  36643. }
  36644. if (this.uvs4) {
  36645. serializationObject.uvs4 = this.uvs4;
  36646. }
  36647. if (this.uvs5) {
  36648. serializationObject.uvs5 = this.uvs5;
  36649. }
  36650. if (this.uvs6) {
  36651. serializationObject.uvs6 = this.uvs6;
  36652. }
  36653. if (this.colors) {
  36654. serializationObject.colors = this.colors;
  36655. }
  36656. if (this.matricesIndices) {
  36657. serializationObject.matricesIndices = this.matricesIndices;
  36658. serializationObject.matricesIndices._isExpanded = true;
  36659. }
  36660. if (this.matricesWeights) {
  36661. serializationObject.matricesWeights = this.matricesWeights;
  36662. }
  36663. if (this.matricesIndicesExtra) {
  36664. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36665. serializationObject.matricesIndicesExtra._isExpanded = true;
  36666. }
  36667. if (this.matricesWeightsExtra) {
  36668. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36669. }
  36670. serializationObject.indices = this.indices;
  36671. return serializationObject;
  36672. };
  36673. // Statics
  36674. /**
  36675. * Extracts the vertexData from a mesh
  36676. * @param mesh the mesh from which to extract the VertexData
  36677. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36678. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36679. * @returns the object VertexData associated to the passed mesh
  36680. */
  36681. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36682. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36683. };
  36684. /**
  36685. * Extracts the vertexData from the geometry
  36686. * @param geometry the geometry from which to extract the VertexData
  36687. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36688. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36689. * @returns the object VertexData associated to the passed mesh
  36690. */
  36691. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36692. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36693. };
  36694. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36695. var result = new VertexData();
  36696. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36697. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36698. }
  36699. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36700. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36701. }
  36702. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36703. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36704. }
  36705. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36706. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36707. }
  36708. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36709. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36710. }
  36711. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36712. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36713. }
  36714. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36715. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36716. }
  36717. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36718. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36719. }
  36720. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36721. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36722. }
  36723. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36724. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36725. }
  36726. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36727. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36728. }
  36729. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36730. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36731. }
  36732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36733. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36734. }
  36735. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36736. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36737. }
  36738. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36739. return result;
  36740. };
  36741. /**
  36742. * Creates the VertexData for a Ribbon
  36743. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36744. * * pathArray array of paths, each of which an array of successive Vector3
  36745. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36746. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36747. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36748. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36749. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36750. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36751. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36752. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36753. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36754. * @returns the VertexData of the ribbon
  36755. */
  36756. VertexData.CreateRibbon = function (options) {
  36757. var pathArray = options.pathArray;
  36758. var closeArray = options.closeArray || false;
  36759. var closePath = options.closePath || false;
  36760. var invertUV = options.invertUV || false;
  36761. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36762. var offset = options.offset || defaultOffset;
  36763. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36764. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36765. var customUV = options.uvs;
  36766. var customColors = options.colors;
  36767. var positions = [];
  36768. var indices = [];
  36769. var normals = [];
  36770. var uvs = [];
  36771. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36772. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36773. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36774. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36775. var minlg; // minimal length among all paths from pathArray
  36776. var lg = []; // array of path lengths : nb of vertex per path
  36777. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36778. var p; // path iterator
  36779. var i; // point iterator
  36780. var j; // point iterator
  36781. // if single path in pathArray
  36782. if (pathArray.length < 2) {
  36783. var ar1 = [];
  36784. var ar2 = [];
  36785. for (i = 0; i < pathArray[0].length - offset; i++) {
  36786. ar1.push(pathArray[0][i]);
  36787. ar2.push(pathArray[0][i + offset]);
  36788. }
  36789. pathArray = [ar1, ar2];
  36790. }
  36791. // positions and horizontal distances (u)
  36792. var idc = 0;
  36793. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36794. var path;
  36795. var l;
  36796. minlg = pathArray[0].length;
  36797. var vectlg;
  36798. var dist;
  36799. for (p = 0; p < pathArray.length; p++) {
  36800. uTotalDistance[p] = 0;
  36801. us[p] = [0];
  36802. path = pathArray[p];
  36803. l = path.length;
  36804. minlg = (minlg < l) ? minlg : l;
  36805. j = 0;
  36806. while (j < l) {
  36807. positions.push(path[j].x, path[j].y, path[j].z);
  36808. if (j > 0) {
  36809. vectlg = path[j].subtract(path[j - 1]).length();
  36810. dist = vectlg + uTotalDistance[p];
  36811. us[p].push(dist);
  36812. uTotalDistance[p] = dist;
  36813. }
  36814. j++;
  36815. }
  36816. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36817. j--;
  36818. positions.push(path[0].x, path[0].y, path[0].z);
  36819. vectlg = path[j].subtract(path[0]).length();
  36820. dist = vectlg + uTotalDistance[p];
  36821. us[p].push(dist);
  36822. uTotalDistance[p] = dist;
  36823. }
  36824. lg[p] = l + closePathCorr;
  36825. idx[p] = idc;
  36826. idc += (l + closePathCorr);
  36827. }
  36828. // vertical distances (v)
  36829. var path1;
  36830. var path2;
  36831. var vertex1 = null;
  36832. var vertex2 = null;
  36833. for (i = 0; i < minlg + closePathCorr; i++) {
  36834. vTotalDistance[i] = 0;
  36835. vs[i] = [0];
  36836. for (p = 0; p < pathArray.length - 1; p++) {
  36837. path1 = pathArray[p];
  36838. path2 = pathArray[p + 1];
  36839. if (i === minlg) { // closePath
  36840. vertex1 = path1[0];
  36841. vertex2 = path2[0];
  36842. }
  36843. else {
  36844. vertex1 = path1[i];
  36845. vertex2 = path2[i];
  36846. }
  36847. vectlg = vertex2.subtract(vertex1).length();
  36848. dist = vectlg + vTotalDistance[i];
  36849. vs[i].push(dist);
  36850. vTotalDistance[i] = dist;
  36851. }
  36852. if (closeArray && vertex2 && vertex1) {
  36853. path1 = pathArray[p];
  36854. path2 = pathArray[0];
  36855. if (i === minlg) { // closePath
  36856. vertex2 = path2[0];
  36857. }
  36858. vectlg = vertex2.subtract(vertex1).length();
  36859. dist = vectlg + vTotalDistance[i];
  36860. vTotalDistance[i] = dist;
  36861. }
  36862. }
  36863. // uvs
  36864. var u;
  36865. var v;
  36866. if (customUV) {
  36867. for (p = 0; p < customUV.length; p++) {
  36868. uvs.push(customUV[p].x, customUV[p].y);
  36869. }
  36870. }
  36871. else {
  36872. for (p = 0; p < pathArray.length; p++) {
  36873. for (i = 0; i < minlg + closePathCorr; i++) {
  36874. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36875. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36876. if (invertUV) {
  36877. uvs.push(v, u);
  36878. }
  36879. else {
  36880. uvs.push(u, v);
  36881. }
  36882. }
  36883. }
  36884. }
  36885. // indices
  36886. p = 0; // path index
  36887. var pi = 0; // positions array index
  36888. var l1 = lg[p] - 1; // path1 length
  36889. var l2 = lg[p + 1] - 1; // path2 length
  36890. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36891. var shft = idx[1] - idx[0]; // shift
  36892. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36893. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36894. // 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
  36895. indices.push(pi, pi + shft, pi + 1);
  36896. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36897. pi += 1;
  36898. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36899. p++;
  36900. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36901. shft = idx[0] - idx[p];
  36902. l1 = lg[p] - 1;
  36903. l2 = lg[0] - 1;
  36904. }
  36905. else {
  36906. shft = idx[p + 1] - idx[p];
  36907. l1 = lg[p] - 1;
  36908. l2 = lg[p + 1] - 1;
  36909. }
  36910. pi = idx[p];
  36911. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36912. }
  36913. }
  36914. // normals
  36915. VertexData.ComputeNormals(positions, indices, normals);
  36916. if (closePath) { // update both the first and last vertex normals to their average value
  36917. var indexFirst = 0;
  36918. var indexLast = 0;
  36919. for (p = 0; p < pathArray.length; p++) {
  36920. indexFirst = idx[p] * 3;
  36921. if (p + 1 < pathArray.length) {
  36922. indexLast = (idx[p + 1] - 1) * 3;
  36923. }
  36924. else {
  36925. indexLast = normals.length - 3;
  36926. }
  36927. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36928. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36929. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36930. normals[indexLast] = normals[indexFirst];
  36931. normals[indexLast + 1] = normals[indexFirst + 1];
  36932. normals[indexLast + 2] = normals[indexFirst + 2];
  36933. }
  36934. }
  36935. // sides
  36936. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36937. // Colors
  36938. var colors = null;
  36939. if (customColors) {
  36940. colors = new Float32Array(customColors.length * 4);
  36941. for (var c = 0; c < customColors.length; c++) {
  36942. colors[c * 4] = customColors[c].r;
  36943. colors[c * 4 + 1] = customColors[c].g;
  36944. colors[c * 4 + 2] = customColors[c].b;
  36945. colors[c * 4 + 3] = customColors[c].a;
  36946. }
  36947. }
  36948. // Result
  36949. var vertexData = new VertexData();
  36950. var positions32 = new Float32Array(positions);
  36951. var normals32 = new Float32Array(normals);
  36952. var uvs32 = new Float32Array(uvs);
  36953. vertexData.indices = indices;
  36954. vertexData.positions = positions32;
  36955. vertexData.normals = normals32;
  36956. vertexData.uvs = uvs32;
  36957. if (colors) {
  36958. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36959. }
  36960. if (closePath) {
  36961. vertexData._idx = idx;
  36962. }
  36963. return vertexData;
  36964. };
  36965. /**
  36966. * Creates the VertexData for a box
  36967. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36968. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36969. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36970. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36971. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36972. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36973. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36974. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36975. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36976. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36977. * @returns the VertexData of the box
  36978. */
  36979. VertexData.CreateBox = function (options) {
  36980. var normalsSource = [
  36981. new BABYLON.Vector3(0, 0, 1),
  36982. new BABYLON.Vector3(0, 0, -1),
  36983. new BABYLON.Vector3(1, 0, 0),
  36984. new BABYLON.Vector3(-1, 0, 0),
  36985. new BABYLON.Vector3(0, 1, 0),
  36986. new BABYLON.Vector3(0, -1, 0)
  36987. ];
  36988. var indices = [];
  36989. var positions = [];
  36990. var normals = [];
  36991. var uvs = [];
  36992. var width = options.width || options.size || 1;
  36993. var height = options.height || options.size || 1;
  36994. var depth = options.depth || options.size || 1;
  36995. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36996. var faceUV = options.faceUV || new Array(6);
  36997. var faceColors = options.faceColors;
  36998. var colors = [];
  36999. // default face colors and UV if undefined
  37000. for (var f = 0; f < 6; f++) {
  37001. if (faceUV[f] === undefined) {
  37002. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37003. }
  37004. if (faceColors && faceColors[f] === undefined) {
  37005. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37006. }
  37007. }
  37008. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37009. // Create each face in turn.
  37010. for (var index = 0; index < normalsSource.length; index++) {
  37011. var normal = normalsSource[index];
  37012. // Get two vectors perpendicular to the face normal and to each other.
  37013. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37014. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37015. // Six indices (two triangles) per face.
  37016. var verticesLength = positions.length / 3;
  37017. indices.push(verticesLength);
  37018. indices.push(verticesLength + 1);
  37019. indices.push(verticesLength + 2);
  37020. indices.push(verticesLength);
  37021. indices.push(verticesLength + 2);
  37022. indices.push(verticesLength + 3);
  37023. // Four vertices per face.
  37024. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37025. positions.push(vertex.x, vertex.y, vertex.z);
  37026. normals.push(normal.x, normal.y, normal.z);
  37027. uvs.push(faceUV[index].z, faceUV[index].w);
  37028. if (faceColors) {
  37029. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37030. }
  37031. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37032. positions.push(vertex.x, vertex.y, vertex.z);
  37033. normals.push(normal.x, normal.y, normal.z);
  37034. uvs.push(faceUV[index].x, faceUV[index].w);
  37035. if (faceColors) {
  37036. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37037. }
  37038. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37039. positions.push(vertex.x, vertex.y, vertex.z);
  37040. normals.push(normal.x, normal.y, normal.z);
  37041. uvs.push(faceUV[index].x, faceUV[index].y);
  37042. if (faceColors) {
  37043. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37044. }
  37045. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37046. positions.push(vertex.x, vertex.y, vertex.z);
  37047. normals.push(normal.x, normal.y, normal.z);
  37048. uvs.push(faceUV[index].z, faceUV[index].y);
  37049. if (faceColors) {
  37050. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37051. }
  37052. }
  37053. // sides
  37054. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37055. // Result
  37056. var vertexData = new VertexData();
  37057. vertexData.indices = indices;
  37058. vertexData.positions = positions;
  37059. vertexData.normals = normals;
  37060. vertexData.uvs = uvs;
  37061. if (faceColors) {
  37062. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37063. vertexData.colors = totalColors;
  37064. }
  37065. return vertexData;
  37066. };
  37067. /**
  37068. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37069. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37070. * * segments sets the number of horizontal strips optional, default 32
  37071. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37072. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37073. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37074. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37075. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37076. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37077. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37078. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37079. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37080. * @returns the VertexData of the ellipsoid
  37081. */
  37082. VertexData.CreateSphere = function (options) {
  37083. var segments = options.segments || 32;
  37084. var diameterX = options.diameterX || options.diameter || 1;
  37085. var diameterY = options.diameterY || options.diameter || 1;
  37086. var diameterZ = options.diameterZ || options.diameter || 1;
  37087. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37088. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37089. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37090. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37091. var totalZRotationSteps = 2 + segments;
  37092. var totalYRotationSteps = 2 * totalZRotationSteps;
  37093. var indices = [];
  37094. var positions = [];
  37095. var normals = [];
  37096. var uvs = [];
  37097. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37098. var normalizedZ = zRotationStep / totalZRotationSteps;
  37099. var angleZ = normalizedZ * Math.PI * slice;
  37100. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37101. var normalizedY = yRotationStep / totalYRotationSteps;
  37102. var angleY = normalizedY * Math.PI * 2 * arc;
  37103. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37104. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37105. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37106. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37107. var vertex = complete.multiply(radius);
  37108. var normal = complete.divide(radius).normalize();
  37109. positions.push(vertex.x, vertex.y, vertex.z);
  37110. normals.push(normal.x, normal.y, normal.z);
  37111. uvs.push(normalizedY, normalizedZ);
  37112. }
  37113. if (zRotationStep > 0) {
  37114. var verticesCount = positions.length / 3;
  37115. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37116. indices.push((firstIndex));
  37117. indices.push((firstIndex + 1));
  37118. indices.push(firstIndex + totalYRotationSteps + 1);
  37119. indices.push((firstIndex + totalYRotationSteps + 1));
  37120. indices.push((firstIndex + 1));
  37121. indices.push((firstIndex + totalYRotationSteps + 2));
  37122. }
  37123. }
  37124. }
  37125. // Sides
  37126. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37127. // Result
  37128. var vertexData = new VertexData();
  37129. vertexData.indices = indices;
  37130. vertexData.positions = positions;
  37131. vertexData.normals = normals;
  37132. vertexData.uvs = uvs;
  37133. return vertexData;
  37134. };
  37135. /**
  37136. * Creates the VertexData for a cylinder, cone or prism
  37137. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37138. * * height sets the height (y direction) of the cylinder, optional, default 2
  37139. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37140. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37141. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37142. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37143. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37144. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37145. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37146. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37147. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37148. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37149. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37150. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37151. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37152. * @returns the VertexData of the cylinder, cone or prism
  37153. */
  37154. VertexData.CreateCylinder = function (options) {
  37155. var height = options.height || 2;
  37156. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37157. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37158. var tessellation = options.tessellation || 24;
  37159. var subdivisions = options.subdivisions || 1;
  37160. var hasRings = options.hasRings ? true : false;
  37161. var enclose = options.enclose ? true : false;
  37162. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37163. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37164. var faceUV = options.faceUV || new Array(3);
  37165. var faceColors = options.faceColors;
  37166. // default face colors and UV if undefined
  37167. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37168. var ringNb = (hasRings) ? subdivisions : 1;
  37169. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37170. var f;
  37171. for (f = 0; f < surfaceNb; f++) {
  37172. if (faceColors && faceColors[f] === undefined) {
  37173. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37174. }
  37175. }
  37176. for (f = 0; f < surfaceNb; f++) {
  37177. if (faceUV && faceUV[f] === undefined) {
  37178. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37179. }
  37180. }
  37181. var indices = new Array();
  37182. var positions = new Array();
  37183. var normals = new Array();
  37184. var uvs = new Array();
  37185. var colors = new Array();
  37186. var angle_step = Math.PI * 2 * arc / tessellation;
  37187. var angle;
  37188. var h;
  37189. var radius;
  37190. var tan = (diameterBottom - diameterTop) / 2 / height;
  37191. var ringVertex = BABYLON.Vector3.Zero();
  37192. var ringNormal = BABYLON.Vector3.Zero();
  37193. var ringFirstVertex = BABYLON.Vector3.Zero();
  37194. var ringFirstNormal = BABYLON.Vector3.Zero();
  37195. var quadNormal = BABYLON.Vector3.Zero();
  37196. var Y = BABYLON.Axis.Y;
  37197. // positions, normals, uvs
  37198. var i;
  37199. var j;
  37200. var r;
  37201. var ringIdx = 1;
  37202. var s = 1; // surface index
  37203. var cs = 0;
  37204. var v = 0;
  37205. for (i = 0; i <= subdivisions; i++) {
  37206. h = i / subdivisions;
  37207. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37208. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37209. for (r = 0; r < ringIdx; r++) {
  37210. if (hasRings) {
  37211. s += r;
  37212. }
  37213. if (enclose) {
  37214. s += 2 * r;
  37215. }
  37216. for (j = 0; j <= tessellation; j++) {
  37217. angle = j * angle_step;
  37218. // position
  37219. ringVertex.x = Math.cos(-angle) * radius;
  37220. ringVertex.y = -height / 2 + h * height;
  37221. ringVertex.z = Math.sin(-angle) * radius;
  37222. // normal
  37223. if (diameterTop === 0 && i === subdivisions) {
  37224. // if no top cap, reuse former normals
  37225. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37226. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37227. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37228. }
  37229. else {
  37230. ringNormal.x = ringVertex.x;
  37231. ringNormal.z = ringVertex.z;
  37232. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37233. ringNormal.normalize();
  37234. }
  37235. // keep first ring vertex values for enclose
  37236. if (j === 0) {
  37237. ringFirstVertex.copyFrom(ringVertex);
  37238. ringFirstNormal.copyFrom(ringNormal);
  37239. }
  37240. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37241. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37242. if (hasRings) {
  37243. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37244. }
  37245. else {
  37246. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37247. }
  37248. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37249. if (faceColors) {
  37250. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37251. }
  37252. }
  37253. // if enclose, add four vertices and their dedicated normals
  37254. if (arc !== 1 && enclose) {
  37255. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37256. positions.push(0, ringVertex.y, 0);
  37257. positions.push(0, ringVertex.y, 0);
  37258. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37259. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37260. quadNormal.normalize();
  37261. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37262. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37263. quadNormal.normalize();
  37264. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37265. if (hasRings) {
  37266. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37267. }
  37268. else {
  37269. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37270. }
  37271. uvs.push(faceUV[s + 1].x, v);
  37272. uvs.push(faceUV[s + 1].z, v);
  37273. if (hasRings) {
  37274. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37275. }
  37276. else {
  37277. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37278. }
  37279. uvs.push(faceUV[s + 2].x, v);
  37280. uvs.push(faceUV[s + 2].z, v);
  37281. if (faceColors) {
  37282. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37283. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37284. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37285. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37286. }
  37287. }
  37288. if (cs !== s) {
  37289. cs = s;
  37290. }
  37291. }
  37292. }
  37293. // indices
  37294. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37295. var s;
  37296. i = 0;
  37297. for (s = 0; s < subdivisions; s++) {
  37298. var i0 = 0;
  37299. var i1 = 0;
  37300. var i2 = 0;
  37301. var i3 = 0;
  37302. for (j = 0; j < tessellation; j++) {
  37303. i0 = i * (e + 1) + j;
  37304. i1 = (i + 1) * (e + 1) + j;
  37305. i2 = i * (e + 1) + (j + 1);
  37306. i3 = (i + 1) * (e + 1) + (j + 1);
  37307. indices.push(i0, i1, i2);
  37308. indices.push(i3, i2, i1);
  37309. }
  37310. if (arc !== 1 && enclose) { // if enclose, add two quads
  37311. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37312. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37313. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37314. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37315. }
  37316. i = (hasRings) ? (i + 2) : (i + 1);
  37317. }
  37318. // Caps
  37319. var createCylinderCap = function (isTop) {
  37320. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37321. if (radius === 0) {
  37322. return;
  37323. }
  37324. // Cap positions, normals & uvs
  37325. var angle;
  37326. var circleVector;
  37327. var i;
  37328. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37329. var c = null;
  37330. if (faceColors) {
  37331. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37332. }
  37333. // cap center
  37334. var vbase = positions.length / 3;
  37335. var offset = isTop ? height / 2 : -height / 2;
  37336. var center = new BABYLON.Vector3(0, offset, 0);
  37337. positions.push(center.x, center.y, center.z);
  37338. normals.push(0, isTop ? 1 : -1, 0);
  37339. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37340. if (c) {
  37341. colors.push(c.r, c.g, c.b, c.a);
  37342. }
  37343. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37344. for (i = 0; i <= tessellation; i++) {
  37345. angle = Math.PI * 2 * i * arc / tessellation;
  37346. var cos = Math.cos(-angle);
  37347. var sin = Math.sin(-angle);
  37348. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37349. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37350. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37351. normals.push(0, isTop ? 1 : -1, 0);
  37352. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37353. if (c) {
  37354. colors.push(c.r, c.g, c.b, c.a);
  37355. }
  37356. }
  37357. // Cap indices
  37358. for (i = 0; i < tessellation; i++) {
  37359. if (!isTop) {
  37360. indices.push(vbase);
  37361. indices.push(vbase + (i + 1));
  37362. indices.push(vbase + (i + 2));
  37363. }
  37364. else {
  37365. indices.push(vbase);
  37366. indices.push(vbase + (i + 2));
  37367. indices.push(vbase + (i + 1));
  37368. }
  37369. }
  37370. };
  37371. // add caps to geometry
  37372. createCylinderCap(false);
  37373. createCylinderCap(true);
  37374. // Sides
  37375. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37376. var vertexData = new VertexData();
  37377. vertexData.indices = indices;
  37378. vertexData.positions = positions;
  37379. vertexData.normals = normals;
  37380. vertexData.uvs = uvs;
  37381. if (faceColors) {
  37382. vertexData.colors = colors;
  37383. }
  37384. return vertexData;
  37385. };
  37386. /**
  37387. * Creates the VertexData for a torus
  37388. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37389. * * diameter the diameter of the torus, optional default 1
  37390. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37391. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37392. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37393. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37394. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37395. * @returns the VertexData of the torus
  37396. */
  37397. VertexData.CreateTorus = function (options) {
  37398. var indices = [];
  37399. var positions = [];
  37400. var normals = [];
  37401. var uvs = [];
  37402. var diameter = options.diameter || 1;
  37403. var thickness = options.thickness || 0.5;
  37404. var tessellation = options.tessellation || 16;
  37405. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37406. var stride = tessellation + 1;
  37407. for (var i = 0; i <= tessellation; i++) {
  37408. var u = i / tessellation;
  37409. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37410. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37411. for (var j = 0; j <= tessellation; j++) {
  37412. var v = 1 - j / tessellation;
  37413. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37414. var dx = Math.cos(innerAngle);
  37415. var dy = Math.sin(innerAngle);
  37416. // Create a vertex.
  37417. var normal = new BABYLON.Vector3(dx, dy, 0);
  37418. var position = normal.scale(thickness / 2);
  37419. var textureCoordinate = new BABYLON.Vector2(u, v);
  37420. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37421. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37422. positions.push(position.x, position.y, position.z);
  37423. normals.push(normal.x, normal.y, normal.z);
  37424. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37425. // And create indices for two triangles.
  37426. var nextI = (i + 1) % stride;
  37427. var nextJ = (j + 1) % stride;
  37428. indices.push(i * stride + j);
  37429. indices.push(i * stride + nextJ);
  37430. indices.push(nextI * stride + j);
  37431. indices.push(i * stride + nextJ);
  37432. indices.push(nextI * stride + nextJ);
  37433. indices.push(nextI * stride + j);
  37434. }
  37435. }
  37436. // Sides
  37437. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37438. // Result
  37439. var vertexData = new VertexData();
  37440. vertexData.indices = indices;
  37441. vertexData.positions = positions;
  37442. vertexData.normals = normals;
  37443. vertexData.uvs = uvs;
  37444. return vertexData;
  37445. };
  37446. /**
  37447. * Creates the VertexData of the LineSystem
  37448. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37449. * - lines an array of lines, each line being an array of successive Vector3
  37450. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37451. * @returns the VertexData of the LineSystem
  37452. */
  37453. VertexData.CreateLineSystem = function (options) {
  37454. var indices = [];
  37455. var positions = [];
  37456. var lines = options.lines;
  37457. var colors = options.colors;
  37458. var vertexColors = [];
  37459. var idx = 0;
  37460. for (var l = 0; l < lines.length; l++) {
  37461. var points = lines[l];
  37462. for (var index = 0; index < points.length; index++) {
  37463. positions.push(points[index].x, points[index].y, points[index].z);
  37464. if (colors) {
  37465. var color = colors[l];
  37466. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37467. }
  37468. if (index > 0) {
  37469. indices.push(idx - 1);
  37470. indices.push(idx);
  37471. }
  37472. idx++;
  37473. }
  37474. }
  37475. var vertexData = new VertexData();
  37476. vertexData.indices = indices;
  37477. vertexData.positions = positions;
  37478. if (colors) {
  37479. vertexData.colors = vertexColors;
  37480. }
  37481. return vertexData;
  37482. };
  37483. /**
  37484. * Create the VertexData for a DashedLines
  37485. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37486. * - points an array successive Vector3
  37487. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37488. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37489. * - dashNb the intended total number of dashes, optional, default 200
  37490. * @returns the VertexData for the DashedLines
  37491. */
  37492. VertexData.CreateDashedLines = function (options) {
  37493. var dashSize = options.dashSize || 3;
  37494. var gapSize = options.gapSize || 1;
  37495. var dashNb = options.dashNb || 200;
  37496. var points = options.points;
  37497. var positions = new Array();
  37498. var indices = new Array();
  37499. var curvect = BABYLON.Vector3.Zero();
  37500. var lg = 0;
  37501. var nb = 0;
  37502. var shft = 0;
  37503. var dashshft = 0;
  37504. var curshft = 0;
  37505. var idx = 0;
  37506. var i = 0;
  37507. for (i = 0; i < points.length - 1; i++) {
  37508. points[i + 1].subtractToRef(points[i], curvect);
  37509. lg += curvect.length();
  37510. }
  37511. shft = lg / dashNb;
  37512. dashshft = dashSize * shft / (dashSize + gapSize);
  37513. for (i = 0; i < points.length - 1; i++) {
  37514. points[i + 1].subtractToRef(points[i], curvect);
  37515. nb = Math.floor(curvect.length() / shft);
  37516. curvect.normalize();
  37517. for (var j = 0; j < nb; j++) {
  37518. curshft = shft * j;
  37519. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37520. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37521. indices.push(idx, idx + 1);
  37522. idx += 2;
  37523. }
  37524. }
  37525. // Result
  37526. var vertexData = new VertexData();
  37527. vertexData.positions = positions;
  37528. vertexData.indices = indices;
  37529. return vertexData;
  37530. };
  37531. /**
  37532. * Creates the VertexData for a Ground
  37533. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37534. * - width the width (x direction) of the ground, optional, default 1
  37535. * - height the height (z direction) of the ground, optional, default 1
  37536. * - subdivisions the number of subdivisions per side, optional, default 1
  37537. * @returns the VertexData of the Ground
  37538. */
  37539. VertexData.CreateGround = function (options) {
  37540. var indices = [];
  37541. var positions = [];
  37542. var normals = [];
  37543. var uvs = [];
  37544. var row, col;
  37545. var width = options.width || 1;
  37546. var height = options.height || 1;
  37547. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37548. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37549. for (row = 0; row <= subdivisionsY; row++) {
  37550. for (col = 0; col <= subdivisionsX; col++) {
  37551. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37552. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37553. positions.push(position.x, position.y, position.z);
  37554. normals.push(normal.x, normal.y, normal.z);
  37555. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37556. }
  37557. }
  37558. for (row = 0; row < subdivisionsY; row++) {
  37559. for (col = 0; col < subdivisionsX; col++) {
  37560. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37561. indices.push(col + 1 + row * (subdivisionsX + 1));
  37562. indices.push(col + row * (subdivisionsX + 1));
  37563. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37564. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37565. indices.push(col + row * (subdivisionsX + 1));
  37566. }
  37567. }
  37568. // Result
  37569. var vertexData = new VertexData();
  37570. vertexData.indices = indices;
  37571. vertexData.positions = positions;
  37572. vertexData.normals = normals;
  37573. vertexData.uvs = uvs;
  37574. return vertexData;
  37575. };
  37576. /**
  37577. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37578. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37579. * * xmin the ground minimum X coordinate, optional, default -1
  37580. * * zmin the ground minimum Z coordinate, optional, default -1
  37581. * * xmax the ground maximum X coordinate, optional, default 1
  37582. * * zmax the ground maximum Z coordinate, optional, default 1
  37583. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37584. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37585. * @returns the VertexData of the TiledGround
  37586. */
  37587. VertexData.CreateTiledGround = function (options) {
  37588. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37589. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37590. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37591. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37592. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37593. var precision = options.precision || { w: 1, h: 1 };
  37594. var indices = new Array();
  37595. var positions = new Array();
  37596. var normals = new Array();
  37597. var uvs = new Array();
  37598. var row, col, tileRow, tileCol;
  37599. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37600. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37601. precision.w = (precision.w < 1) ? 1 : precision.w;
  37602. precision.h = (precision.h < 1) ? 1 : precision.h;
  37603. var tileSize = {
  37604. 'w': (xmax - xmin) / subdivisions.w,
  37605. 'h': (zmax - zmin) / subdivisions.h
  37606. };
  37607. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37608. // Indices
  37609. var base = positions.length / 3;
  37610. var rowLength = precision.w + 1;
  37611. for (row = 0; row < precision.h; row++) {
  37612. for (col = 0; col < precision.w; col++) {
  37613. var square = [
  37614. base + col + row * rowLength,
  37615. base + (col + 1) + row * rowLength,
  37616. base + (col + 1) + (row + 1) * rowLength,
  37617. base + col + (row + 1) * rowLength
  37618. ];
  37619. indices.push(square[1]);
  37620. indices.push(square[2]);
  37621. indices.push(square[3]);
  37622. indices.push(square[0]);
  37623. indices.push(square[1]);
  37624. indices.push(square[3]);
  37625. }
  37626. }
  37627. // Position, normals and uvs
  37628. var position = BABYLON.Vector3.Zero();
  37629. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37630. for (row = 0; row <= precision.h; row++) {
  37631. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37632. for (col = 0; col <= precision.w; col++) {
  37633. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37634. position.y = 0;
  37635. positions.push(position.x, position.y, position.z);
  37636. normals.push(normal.x, normal.y, normal.z);
  37637. uvs.push(col / precision.w, row / precision.h);
  37638. }
  37639. }
  37640. }
  37641. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37642. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37643. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37644. }
  37645. }
  37646. // Result
  37647. var vertexData = new VertexData();
  37648. vertexData.indices = indices;
  37649. vertexData.positions = positions;
  37650. vertexData.normals = normals;
  37651. vertexData.uvs = uvs;
  37652. return vertexData;
  37653. };
  37654. /**
  37655. * Creates the VertexData of the Ground designed from a heightmap
  37656. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37657. * * width the width (x direction) of the ground
  37658. * * height the height (z direction) of the ground
  37659. * * subdivisions the number of subdivisions per side
  37660. * * minHeight the minimum altitude on the ground, optional, default 0
  37661. * * maxHeight the maximum altitude on the ground, optional default 1
  37662. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37663. * * buffer the array holding the image color data
  37664. * * bufferWidth the width of image
  37665. * * bufferHeight the height of image
  37666. * @returns the VertexData of the Ground designed from a heightmap
  37667. */
  37668. VertexData.CreateGroundFromHeightMap = function (options) {
  37669. var indices = [];
  37670. var positions = [];
  37671. var normals = [];
  37672. var uvs = [];
  37673. var row, col;
  37674. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37675. // Vertices
  37676. for (row = 0; row <= options.subdivisions; row++) {
  37677. for (col = 0; col <= options.subdivisions; col++) {
  37678. 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));
  37679. // Compute height
  37680. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37681. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37682. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37683. var r = options.buffer[pos] / 255.0;
  37684. var g = options.buffer[pos + 1] / 255.0;
  37685. var b = options.buffer[pos + 2] / 255.0;
  37686. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37687. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37688. // Add vertex
  37689. positions.push(position.x, position.y, position.z);
  37690. normals.push(0, 0, 0);
  37691. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37692. }
  37693. }
  37694. // Indices
  37695. for (row = 0; row < options.subdivisions; row++) {
  37696. for (col = 0; col < options.subdivisions; col++) {
  37697. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37698. indices.push(col + 1 + row * (options.subdivisions + 1));
  37699. indices.push(col + row * (options.subdivisions + 1));
  37700. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37701. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37702. indices.push(col + row * (options.subdivisions + 1));
  37703. }
  37704. }
  37705. // Normals
  37706. VertexData.ComputeNormals(positions, indices, normals);
  37707. // Result
  37708. var vertexData = new VertexData();
  37709. vertexData.indices = indices;
  37710. vertexData.positions = positions;
  37711. vertexData.normals = normals;
  37712. vertexData.uvs = uvs;
  37713. return vertexData;
  37714. };
  37715. /**
  37716. * Creates the VertexData for a Plane
  37717. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37718. * * size sets the width and height of the plane to the value of size, optional default 1
  37719. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37720. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37721. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37722. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37723. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37724. * @returns the VertexData of the box
  37725. */
  37726. VertexData.CreatePlane = function (options) {
  37727. var indices = [];
  37728. var positions = [];
  37729. var normals = [];
  37730. var uvs = [];
  37731. var width = options.width || options.size || 1;
  37732. var height = options.height || options.size || 1;
  37733. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37734. // Vertices
  37735. var halfWidth = width / 2.0;
  37736. var halfHeight = height / 2.0;
  37737. positions.push(-halfWidth, -halfHeight, 0);
  37738. normals.push(0, 0, -1.0);
  37739. uvs.push(0.0, 0.0);
  37740. positions.push(halfWidth, -halfHeight, 0);
  37741. normals.push(0, 0, -1.0);
  37742. uvs.push(1.0, 0.0);
  37743. positions.push(halfWidth, halfHeight, 0);
  37744. normals.push(0, 0, -1.0);
  37745. uvs.push(1.0, 1.0);
  37746. positions.push(-halfWidth, halfHeight, 0);
  37747. normals.push(0, 0, -1.0);
  37748. uvs.push(0.0, 1.0);
  37749. // Indices
  37750. indices.push(0);
  37751. indices.push(1);
  37752. indices.push(2);
  37753. indices.push(0);
  37754. indices.push(2);
  37755. indices.push(3);
  37756. // Sides
  37757. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37758. // Result
  37759. var vertexData = new VertexData();
  37760. vertexData.indices = indices;
  37761. vertexData.positions = positions;
  37762. vertexData.normals = normals;
  37763. vertexData.uvs = uvs;
  37764. return vertexData;
  37765. };
  37766. /**
  37767. * Creates the VertexData of the Disc or regular Polygon
  37768. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37769. * * radius the radius of the disc, optional default 0.5
  37770. * * tessellation the number of polygon sides, optional, default 64
  37771. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37772. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37773. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37774. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37775. * @returns the VertexData of the box
  37776. */
  37777. VertexData.CreateDisc = function (options) {
  37778. var positions = new Array();
  37779. var indices = new Array();
  37780. var normals = new Array();
  37781. var uvs = new Array();
  37782. var radius = options.radius || 0.5;
  37783. var tessellation = options.tessellation || 64;
  37784. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37786. // positions and uvs
  37787. positions.push(0, 0, 0); // disc center first
  37788. uvs.push(0.5, 0.5);
  37789. var theta = Math.PI * 2 * arc;
  37790. var step = theta / tessellation;
  37791. for (var a = 0; a < theta; a += step) {
  37792. var x = Math.cos(a);
  37793. var y = Math.sin(a);
  37794. var u = (x + 1) / 2;
  37795. var v = (1 - y) / 2;
  37796. positions.push(radius * x, radius * y, 0);
  37797. uvs.push(u, v);
  37798. }
  37799. if (arc === 1) {
  37800. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37801. uvs.push(uvs[2], uvs[3]);
  37802. }
  37803. //indices
  37804. var vertexNb = positions.length / 3;
  37805. for (var i = 1; i < vertexNb - 1; i++) {
  37806. indices.push(i + 1, 0, i);
  37807. }
  37808. // result
  37809. VertexData.ComputeNormals(positions, indices, normals);
  37810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37811. var vertexData = new VertexData();
  37812. vertexData.indices = indices;
  37813. vertexData.positions = positions;
  37814. vertexData.normals = normals;
  37815. vertexData.uvs = uvs;
  37816. return vertexData;
  37817. };
  37818. /**
  37819. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37820. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37821. * @param polygon a mesh built from polygonTriangulation.build()
  37822. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37823. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37824. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37825. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37826. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37827. * @returns the VertexData of the Polygon
  37828. */
  37829. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37830. var faceUV = fUV || new Array(3);
  37831. var faceColors = fColors;
  37832. var colors = [];
  37833. // default face colors and UV if undefined
  37834. for (var f = 0; f < 3; f++) {
  37835. if (faceUV[f] === undefined) {
  37836. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37837. }
  37838. if (faceColors && faceColors[f] === undefined) {
  37839. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37840. }
  37841. }
  37842. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37843. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37844. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37845. var indices = polygon.getIndices();
  37846. // set face colours and textures
  37847. var idx = 0;
  37848. var face = 0;
  37849. for (var index = 0; index < normals.length; index += 3) {
  37850. //Edge Face no. 1
  37851. if (Math.abs(normals[index + 1]) < 0.001) {
  37852. face = 1;
  37853. }
  37854. //Top Face no. 0
  37855. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37856. face = 0;
  37857. }
  37858. //Bottom Face no. 2
  37859. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37860. face = 2;
  37861. }
  37862. idx = index / 3;
  37863. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37864. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37865. if (faceColors) {
  37866. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37867. }
  37868. }
  37869. // sides
  37870. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37871. // Result
  37872. var vertexData = new VertexData();
  37873. vertexData.indices = indices;
  37874. vertexData.positions = positions;
  37875. vertexData.normals = normals;
  37876. vertexData.uvs = uvs;
  37877. if (faceColors) {
  37878. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37879. vertexData.colors = totalColors;
  37880. }
  37881. return vertexData;
  37882. };
  37883. /**
  37884. * Creates the VertexData of the IcoSphere
  37885. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37886. * * radius the radius of the IcoSphere, optional default 1
  37887. * * radiusX allows stretching in the x direction, optional, default radius
  37888. * * radiusY allows stretching in the y direction, optional, default radius
  37889. * * radiusZ allows stretching in the z direction, optional, default radius
  37890. * * flat when true creates a flat shaded mesh, optional, default true
  37891. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37892. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37893. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37894. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37895. * @returns the VertexData of the IcoSphere
  37896. */
  37897. VertexData.CreateIcoSphere = function (options) {
  37898. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37899. var radius = options.radius || 1;
  37900. var flat = (options.flat === undefined) ? true : options.flat;
  37901. var subdivisions = options.subdivisions || 4;
  37902. var radiusX = options.radiusX || radius;
  37903. var radiusY = options.radiusY || radius;
  37904. var radiusZ = options.radiusZ || radius;
  37905. var t = (1 + Math.sqrt(5)) / 2;
  37906. // 12 vertex x,y,z
  37907. var ico_vertices = [
  37908. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37909. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37910. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37911. ];
  37912. // index of 3 vertex makes a face of icopshere
  37913. var ico_indices = [
  37914. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37915. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37916. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37917. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37918. ];
  37919. // vertex for uv have aliased position, not for UV
  37920. var vertices_unalias_id = [
  37921. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37922. // vertex alias
  37923. 0,
  37924. 2,
  37925. 3,
  37926. 3,
  37927. 3,
  37928. 4,
  37929. 7,
  37930. 8,
  37931. 9,
  37932. 9,
  37933. 10,
  37934. 11 // 23: B + 12
  37935. ];
  37936. // uv as integer step (not pixels !)
  37937. var ico_vertexuv = [
  37938. 5, 1, 3, 1, 6, 4, 0, 0,
  37939. 5, 3, 4, 2, 2, 2, 4, 0,
  37940. 2, 0, 1, 1, 6, 0, 6, 2,
  37941. // vertex alias (for same vertex on different faces)
  37942. 0, 4,
  37943. 3, 3,
  37944. 4, 4,
  37945. 3, 1,
  37946. 4, 2,
  37947. 4, 4,
  37948. 0, 2,
  37949. 1, 1,
  37950. 2, 2,
  37951. 3, 3,
  37952. 1, 3,
  37953. 2, 4 // 23: B + 12
  37954. ];
  37955. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37956. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37957. // First island of uv mapping
  37958. // v = 4h 3+ 2
  37959. // v = 3h 9+ 4
  37960. // v = 2h 9+ 5 B
  37961. // v = 1h 9 1 0
  37962. // v = 0h 3 8 7 A
  37963. // u = 0 1 2 3 4 5 6 *a
  37964. // Second island of uv mapping
  37965. // v = 4h 0+ B+ 4+
  37966. // v = 3h A+ 2+
  37967. // v = 2h 7+ 6 3+
  37968. // v = 1h 8+ 3+
  37969. // v = 0h
  37970. // u = 0 1 2 3 4 5 6 *a
  37971. // Face layout on texture UV mapping
  37972. // ============
  37973. // \ 4 /\ 16 / ======
  37974. // \ / \ / /\ 11 /
  37975. // \/ 7 \/ / \ /
  37976. // ======= / 10 \/
  37977. // /\ 17 /\ =======
  37978. // / \ / \ \ 15 /\
  37979. // / 8 \/ 12 \ \ / \
  37980. // ============ \/ 6 \
  37981. // \ 18 /\ ============
  37982. // \ / \ \ 5 /\ 0 /
  37983. // \/ 13 \ \ / \ /
  37984. // ======= \/ 1 \/
  37985. // =============
  37986. // /\ 19 /\ 2 /\
  37987. // / \ / \ / \
  37988. // / 14 \/ 9 \/ 3 \
  37989. // ===================
  37990. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37991. var ustep = 138 / 1024;
  37992. var vstep = 239 / 1024;
  37993. var uoffset = 60 / 1024;
  37994. var voffset = 26 / 1024;
  37995. // Second island should have margin, not to touch the first island
  37996. // avoid any borderline artefact in pixel rounding
  37997. var island_u_offset = -40 / 1024;
  37998. var island_v_offset = +20 / 1024;
  37999. // face is either island 0 or 1 :
  38000. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38001. var island = [
  38002. 0, 0, 0, 0, 1,
  38003. 0, 0, 1, 1, 0,
  38004. 0, 0, 1, 1, 0,
  38005. 0, 1, 1, 1, 0 // 15 - 19
  38006. ];
  38007. var indices = new Array();
  38008. var positions = new Array();
  38009. var normals = new Array();
  38010. var uvs = new Array();
  38011. var current_indice = 0;
  38012. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38013. var face_vertex_pos = new Array(3);
  38014. var face_vertex_uv = new Array(3);
  38015. var v012;
  38016. for (v012 = 0; v012 < 3; v012++) {
  38017. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38018. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38019. }
  38020. // create all with normals
  38021. for (var face = 0; face < 20; face++) {
  38022. // 3 vertex per face
  38023. for (v012 = 0; v012 < 3; v012++) {
  38024. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38025. var v_id = ico_indices[3 * face + v012];
  38026. // vertex have 3D position (x,y,z)
  38027. 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]);
  38028. // Normalize to get normal, then scale to radius
  38029. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38030. // uv Coordinates from vertex ID
  38031. 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);
  38032. }
  38033. // Subdivide the face (interpolate pos, norm, uv)
  38034. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38035. // - norm is linear interpolation of vertex corner normal
  38036. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38037. // - uv is linear interpolation
  38038. //
  38039. // Topology is as below for sub-divide by 2
  38040. // vertex shown as v0,v1,v2
  38041. // interp index is i1 to progress in range [v0,v1[
  38042. // interp index is i2 to progress in range [v0,v2[
  38043. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38044. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38045. //
  38046. //
  38047. // i2 v2
  38048. // ^ ^
  38049. // / / \
  38050. // / / \
  38051. // / / \
  38052. // / / (0,1) \
  38053. // / #---------\
  38054. // / / \ (0,0)'/ \
  38055. // / / \ / \
  38056. // / / \ / \
  38057. // / / (0,0) \ / (1,0) \
  38058. // / #---------#---------\
  38059. // v0 v1
  38060. //
  38061. // --------------------> i1
  38062. //
  38063. // interp of (i1,i2):
  38064. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38065. // along i1 : lerp(x0,x1, i1/(S-i2))
  38066. //
  38067. // centroid of triangle is needed to get help normal computation
  38068. // (c1,c2) are used for centroid location
  38069. var interp_vertex = function (i1, i2, c1, c2) {
  38070. // vertex is interpolated from
  38071. // - face_vertex_pos[0..2]
  38072. // - face_vertex_uv[0..2]
  38073. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38074. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38075. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38076. pos_interp.normalize();
  38077. var vertex_normal;
  38078. if (flat) {
  38079. // in flat mode, recalculate normal as face centroid normal
  38080. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38081. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38082. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38083. }
  38084. else {
  38085. // in smooth mode, recalculate normal from each single vertex position
  38086. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38087. }
  38088. // Vertex normal need correction due to X,Y,Z radius scaling
  38089. vertex_normal.x /= radiusX;
  38090. vertex_normal.y /= radiusY;
  38091. vertex_normal.z /= radiusZ;
  38092. vertex_normal.normalize();
  38093. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38094. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38095. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38096. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38097. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38098. uvs.push(uv_interp.x, uv_interp.y);
  38099. // push each vertex has member of a face
  38100. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38101. indices.push(current_indice);
  38102. current_indice++;
  38103. };
  38104. for (var i2 = 0; i2 < subdivisions; i2++) {
  38105. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38106. // face : (i1,i2) for /\ :
  38107. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38108. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38109. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38110. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38111. if (i1 + i2 + 1 < subdivisions) {
  38112. // face : (i1,i2)' for \/ :
  38113. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38114. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38115. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38116. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38117. }
  38118. }
  38119. }
  38120. }
  38121. // Sides
  38122. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38123. // Result
  38124. var vertexData = new VertexData();
  38125. vertexData.indices = indices;
  38126. vertexData.positions = positions;
  38127. vertexData.normals = normals;
  38128. vertexData.uvs = uvs;
  38129. return vertexData;
  38130. };
  38131. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38132. /**
  38133. * Creates the VertexData for a Polyhedron
  38134. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38135. * * type provided types are:
  38136. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38137. * * 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)
  38138. * * size the size of the IcoSphere, optional default 1
  38139. * * sizeX allows stretching in the x direction, optional, default size
  38140. * * sizeY allows stretching in the y direction, optional, default size
  38141. * * sizeZ allows stretching in the z direction, optional, default size
  38142. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38143. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38144. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38145. * * flat when true creates a flat shaded mesh, optional, default true
  38146. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38147. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38148. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38149. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38150. * @returns the VertexData of the Polyhedron
  38151. */
  38152. VertexData.CreatePolyhedron = function (options) {
  38153. // provided polyhedron types :
  38154. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38155. // 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)
  38156. var polyhedra = [];
  38157. 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]] };
  38158. 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]] };
  38159. polyhedra[2] = {
  38160. 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]],
  38161. 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]]
  38162. };
  38163. polyhedra[3] = {
  38164. 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]],
  38165. 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]]
  38166. };
  38167. polyhedra[4] = {
  38168. 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]],
  38169. 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]]
  38170. };
  38171. 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]] };
  38172. 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]] };
  38173. 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]] };
  38174. 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]] };
  38175. 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]] };
  38176. 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]] };
  38177. 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]] };
  38178. 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]] };
  38179. 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]] };
  38180. polyhedra[14] = {
  38181. 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]],
  38182. 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]]
  38183. };
  38184. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38185. var size = options.size;
  38186. var sizeX = options.sizeX || size || 1;
  38187. var sizeY = options.sizeY || size || 1;
  38188. var sizeZ = options.sizeZ || size || 1;
  38189. var data = options.custom || polyhedra[type];
  38190. var nbfaces = data.face.length;
  38191. var faceUV = options.faceUV || new Array(nbfaces);
  38192. var faceColors = options.faceColors;
  38193. var flat = (options.flat === undefined) ? true : options.flat;
  38194. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38195. var positions = new Array();
  38196. var indices = new Array();
  38197. var normals = new Array();
  38198. var uvs = new Array();
  38199. var colors = new Array();
  38200. var index = 0;
  38201. var faceIdx = 0; // face cursor in the array "indexes"
  38202. var indexes = new Array();
  38203. var i = 0;
  38204. var f = 0;
  38205. var u, v, ang, x, y, tmp;
  38206. // default face colors and UV if undefined
  38207. if (flat) {
  38208. for (f = 0; f < nbfaces; f++) {
  38209. if (faceColors && faceColors[f] === undefined) {
  38210. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38211. }
  38212. if (faceUV && faceUV[f] === undefined) {
  38213. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38214. }
  38215. }
  38216. }
  38217. if (!flat) {
  38218. for (i = 0; i < data.vertex.length; i++) {
  38219. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38220. uvs.push(0, 0);
  38221. }
  38222. for (f = 0; f < nbfaces; f++) {
  38223. for (i = 0; i < data.face[f].length - 2; i++) {
  38224. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38225. }
  38226. }
  38227. }
  38228. else {
  38229. for (f = 0; f < nbfaces; f++) {
  38230. var fl = data.face[f].length; // number of vertices of the current face
  38231. ang = 2 * Math.PI / fl;
  38232. x = 0.5 * Math.tan(ang / 2);
  38233. y = 0.5;
  38234. // positions, uvs, colors
  38235. for (i = 0; i < fl; i++) {
  38236. // positions
  38237. 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);
  38238. indexes.push(index);
  38239. index++;
  38240. // uvs
  38241. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38242. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38243. uvs.push(u, v);
  38244. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38245. y = x * Math.sin(ang) + y * Math.cos(ang);
  38246. x = tmp;
  38247. // colors
  38248. if (faceColors) {
  38249. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38250. }
  38251. }
  38252. // indices from indexes
  38253. for (i = 0; i < fl - 2; i++) {
  38254. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38255. }
  38256. faceIdx += fl;
  38257. }
  38258. }
  38259. VertexData.ComputeNormals(positions, indices, normals);
  38260. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38261. var vertexData = new VertexData();
  38262. vertexData.positions = positions;
  38263. vertexData.indices = indices;
  38264. vertexData.normals = normals;
  38265. vertexData.uvs = uvs;
  38266. if (faceColors && flat) {
  38267. vertexData.colors = colors;
  38268. }
  38269. return vertexData;
  38270. };
  38271. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38272. /**
  38273. * Creates the VertexData for a TorusKnot
  38274. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38275. * * radius the radius of the torus knot, optional, default 2
  38276. * * tube the thickness of the tube, optional, default 0.5
  38277. * * radialSegments the number of sides on each tube segments, optional, default 32
  38278. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38279. * * p the number of windings around the z axis, optional, default 2
  38280. * * q the number of windings around the x axis, optional, default 3
  38281. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38282. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38283. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38284. * @returns the VertexData of the Torus Knot
  38285. */
  38286. VertexData.CreateTorusKnot = function (options) {
  38287. var indices = new Array();
  38288. var positions = new Array();
  38289. var normals = new Array();
  38290. var uvs = new Array();
  38291. var radius = options.radius || 2;
  38292. var tube = options.tube || 0.5;
  38293. var radialSegments = options.radialSegments || 32;
  38294. var tubularSegments = options.tubularSegments || 32;
  38295. var p = options.p || 2;
  38296. var q = options.q || 3;
  38297. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38298. // Helper
  38299. var getPos = function (angle) {
  38300. var cu = Math.cos(angle);
  38301. var su = Math.sin(angle);
  38302. var quOverP = q / p * angle;
  38303. var cs = Math.cos(quOverP);
  38304. var tx = radius * (2 + cs) * 0.5 * cu;
  38305. var ty = radius * (2 + cs) * su * 0.5;
  38306. var tz = radius * Math.sin(quOverP) * 0.5;
  38307. return new BABYLON.Vector3(tx, ty, tz);
  38308. };
  38309. // Vertices
  38310. var i;
  38311. var j;
  38312. for (i = 0; i <= radialSegments; i++) {
  38313. var modI = i % radialSegments;
  38314. var u = modI / radialSegments * 2 * p * Math.PI;
  38315. var p1 = getPos(u);
  38316. var p2 = getPos(u + 0.01);
  38317. var tang = p2.subtract(p1);
  38318. var n = p2.add(p1);
  38319. var bitan = BABYLON.Vector3.Cross(tang, n);
  38320. n = BABYLON.Vector3.Cross(bitan, tang);
  38321. bitan.normalize();
  38322. n.normalize();
  38323. for (j = 0; j < tubularSegments; j++) {
  38324. var modJ = j % tubularSegments;
  38325. var v = modJ / tubularSegments * 2 * Math.PI;
  38326. var cx = -tube * Math.cos(v);
  38327. var cy = tube * Math.sin(v);
  38328. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38329. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38330. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38331. uvs.push(i / radialSegments);
  38332. uvs.push(j / tubularSegments);
  38333. }
  38334. }
  38335. for (i = 0; i < radialSegments; i++) {
  38336. for (j = 0; j < tubularSegments; j++) {
  38337. var jNext = (j + 1) % tubularSegments;
  38338. var a = i * tubularSegments + j;
  38339. var b = (i + 1) * tubularSegments + j;
  38340. var c = (i + 1) * tubularSegments + jNext;
  38341. var d = i * tubularSegments + jNext;
  38342. indices.push(d);
  38343. indices.push(b);
  38344. indices.push(a);
  38345. indices.push(d);
  38346. indices.push(c);
  38347. indices.push(b);
  38348. }
  38349. }
  38350. // Normals
  38351. VertexData.ComputeNormals(positions, indices, normals);
  38352. // Sides
  38353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38354. // Result
  38355. var vertexData = new VertexData();
  38356. vertexData.indices = indices;
  38357. vertexData.positions = positions;
  38358. vertexData.normals = normals;
  38359. vertexData.uvs = uvs;
  38360. return vertexData;
  38361. };
  38362. // Tools
  38363. /**
  38364. * Compute normals for given positions and indices
  38365. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38366. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38367. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38368. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38369. * * facetNormals : optional array of facet normals (vector3)
  38370. * * facetPositions : optional array of facet positions (vector3)
  38371. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38372. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38373. * * bInfo : optional bounding info, required for facetPartitioning computation
  38374. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38375. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38376. * * useRightHandedSystem: optional boolean to for right handed system computation
  38377. * * depthSort : optional boolean to enable the facet depth sort computation
  38378. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38379. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38380. */
  38381. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38382. // temporary scalar variables
  38383. var index = 0; // facet index
  38384. var p1p2x = 0.0; // p1p2 vector x coordinate
  38385. var p1p2y = 0.0; // p1p2 vector y coordinate
  38386. var p1p2z = 0.0; // p1p2 vector z coordinate
  38387. var p3p2x = 0.0; // p3p2 vector x coordinate
  38388. var p3p2y = 0.0; // p3p2 vector y coordinate
  38389. var p3p2z = 0.0; // p3p2 vector z coordinate
  38390. var faceNormalx = 0.0; // facet normal x coordinate
  38391. var faceNormaly = 0.0; // facet normal y coordinate
  38392. var faceNormalz = 0.0; // facet normal z coordinate
  38393. var length = 0.0; // facet normal length before normalization
  38394. var v1x = 0; // vector1 x index in the positions array
  38395. var v1y = 0; // vector1 y index in the positions array
  38396. var v1z = 0; // vector1 z index in the positions array
  38397. var v2x = 0; // vector2 x index in the positions array
  38398. var v2y = 0; // vector2 y index in the positions array
  38399. var v2z = 0; // vector2 z index in the positions array
  38400. var v3x = 0; // vector3 x index in the positions array
  38401. var v3y = 0; // vector3 y index in the positions array
  38402. var v3z = 0; // vector3 z index in the positions array
  38403. var computeFacetNormals = false;
  38404. var computeFacetPositions = false;
  38405. var computeFacetPartitioning = false;
  38406. var computeDepthSort = false;
  38407. var faceNormalSign = 1;
  38408. var ratio = 0;
  38409. var distanceTo = null;
  38410. if (options) {
  38411. computeFacetNormals = (options.facetNormals) ? true : false;
  38412. computeFacetPositions = (options.facetPositions) ? true : false;
  38413. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38414. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38415. ratio = options.ratio || 0;
  38416. computeDepthSort = (options.depthSort) ? true : false;
  38417. distanceTo = (options.distanceTo);
  38418. if (computeDepthSort) {
  38419. if (distanceTo === undefined) {
  38420. distanceTo = BABYLON.Vector3.Zero();
  38421. }
  38422. var depthSortedFacets = options.depthSortedFacets;
  38423. }
  38424. }
  38425. // facetPartitioning reinit if needed
  38426. var xSubRatio = 0;
  38427. var ySubRatio = 0;
  38428. var zSubRatio = 0;
  38429. var subSq = 0;
  38430. if (computeFacetPartitioning && options && options.bbSize) {
  38431. var ox = 0; // X partitioning index for facet position
  38432. var oy = 0; // Y partinioning index for facet position
  38433. var oz = 0; // Z partinioning index for facet position
  38434. var b1x = 0; // X partitioning index for facet v1 vertex
  38435. var b1y = 0; // Y partitioning index for facet v1 vertex
  38436. var b1z = 0; // z partitioning index for facet v1 vertex
  38437. var b2x = 0; // X partitioning index for facet v2 vertex
  38438. var b2y = 0; // Y partitioning index for facet v2 vertex
  38439. var b2z = 0; // Z partitioning index for facet v2 vertex
  38440. var b3x = 0; // X partitioning index for facet v3 vertex
  38441. var b3y = 0; // Y partitioning index for facet v3 vertex
  38442. var b3z = 0; // Z partitioning index for facet v3 vertex
  38443. var block_idx_o = 0; // facet barycenter block index
  38444. var block_idx_v1 = 0; // v1 vertex block index
  38445. var block_idx_v2 = 0; // v2 vertex block index
  38446. var block_idx_v3 = 0; // v3 vertex block index
  38447. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38448. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38449. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38450. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38451. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38452. subSq = options.subDiv.max * options.subDiv.max;
  38453. options.facetPartitioning.length = 0;
  38454. }
  38455. // reset the normals
  38456. for (index = 0; index < positions.length; index++) {
  38457. normals[index] = 0.0;
  38458. }
  38459. // Loop : 1 indice triplet = 1 facet
  38460. var nbFaces = (indices.length / 3) | 0;
  38461. for (index = 0; index < nbFaces; index++) {
  38462. // get the indexes of the coordinates of each vertex of the facet
  38463. v1x = indices[index * 3] * 3;
  38464. v1y = v1x + 1;
  38465. v1z = v1x + 2;
  38466. v2x = indices[index * 3 + 1] * 3;
  38467. v2y = v2x + 1;
  38468. v2z = v2x + 2;
  38469. v3x = indices[index * 3 + 2] * 3;
  38470. v3y = v3x + 1;
  38471. v3z = v3x + 2;
  38472. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38473. p1p2y = positions[v1y] - positions[v2y];
  38474. p1p2z = positions[v1z] - positions[v2z];
  38475. p3p2x = positions[v3x] - positions[v2x];
  38476. p3p2y = positions[v3y] - positions[v2y];
  38477. p3p2z = positions[v3z] - positions[v2z];
  38478. // compute the face normal with the cross product
  38479. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38480. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38481. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38482. // normalize this normal and store it in the array facetData
  38483. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38484. length = (length === 0) ? 1.0 : length;
  38485. faceNormalx /= length;
  38486. faceNormaly /= length;
  38487. faceNormalz /= length;
  38488. if (computeFacetNormals && options) {
  38489. options.facetNormals[index].x = faceNormalx;
  38490. options.facetNormals[index].y = faceNormaly;
  38491. options.facetNormals[index].z = faceNormalz;
  38492. }
  38493. if (computeFacetPositions && options) {
  38494. // compute and the facet barycenter coordinates in the array facetPositions
  38495. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38496. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38497. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38498. }
  38499. if (computeFacetPartitioning && options) {
  38500. // store the facet indexes in arrays in the main facetPartitioning array :
  38501. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38502. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38503. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38504. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38505. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38506. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38507. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38508. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38509. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38510. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38511. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38512. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38513. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38514. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38515. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38516. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38517. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38518. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38519. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38520. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38521. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38522. // push each facet index in each block containing the vertex
  38523. options.facetPartitioning[block_idx_v1].push(index);
  38524. if (block_idx_v2 != block_idx_v1) {
  38525. options.facetPartitioning[block_idx_v2].push(index);
  38526. }
  38527. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38528. options.facetPartitioning[block_idx_v3].push(index);
  38529. }
  38530. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38531. options.facetPartitioning[block_idx_o].push(index);
  38532. }
  38533. }
  38534. if (computeDepthSort && options && options.facetPositions) {
  38535. var dsf = depthSortedFacets[index];
  38536. dsf.ind = index * 3;
  38537. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38538. }
  38539. // compute the normals anyway
  38540. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38541. normals[v1y] += faceNormaly;
  38542. normals[v1z] += faceNormalz;
  38543. normals[v2x] += faceNormalx;
  38544. normals[v2y] += faceNormaly;
  38545. normals[v2z] += faceNormalz;
  38546. normals[v3x] += faceNormalx;
  38547. normals[v3y] += faceNormaly;
  38548. normals[v3z] += faceNormalz;
  38549. }
  38550. // last normalization of each normal
  38551. for (index = 0; index < normals.length / 3; index++) {
  38552. faceNormalx = normals[index * 3];
  38553. faceNormaly = normals[index * 3 + 1];
  38554. faceNormalz = normals[index * 3 + 2];
  38555. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38556. length = (length === 0) ? 1.0 : length;
  38557. faceNormalx /= length;
  38558. faceNormaly /= length;
  38559. faceNormalz /= length;
  38560. normals[index * 3] = faceNormalx;
  38561. normals[index * 3 + 1] = faceNormaly;
  38562. normals[index * 3 + 2] = faceNormalz;
  38563. }
  38564. };
  38565. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38566. var li = indices.length;
  38567. var ln = normals.length;
  38568. var i;
  38569. var n;
  38570. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38571. switch (sideOrientation) {
  38572. case BABYLON.Mesh.FRONTSIDE:
  38573. // nothing changed
  38574. break;
  38575. case BABYLON.Mesh.BACKSIDE:
  38576. var tmp;
  38577. // indices
  38578. for (i = 0; i < li; i += 3) {
  38579. tmp = indices[i];
  38580. indices[i] = indices[i + 2];
  38581. indices[i + 2] = tmp;
  38582. }
  38583. // normals
  38584. for (n = 0; n < ln; n++) {
  38585. normals[n] = -normals[n];
  38586. }
  38587. break;
  38588. case BABYLON.Mesh.DOUBLESIDE:
  38589. // positions
  38590. var lp = positions.length;
  38591. var l = lp / 3;
  38592. for (var p = 0; p < lp; p++) {
  38593. positions[lp + p] = positions[p];
  38594. }
  38595. // indices
  38596. for (i = 0; i < li; i += 3) {
  38597. indices[i + li] = indices[i + 2] + l;
  38598. indices[i + 1 + li] = indices[i + 1] + l;
  38599. indices[i + 2 + li] = indices[i] + l;
  38600. }
  38601. // normals
  38602. for (n = 0; n < ln; n++) {
  38603. normals[ln + n] = -normals[n];
  38604. }
  38605. // uvs
  38606. var lu = uvs.length;
  38607. var u = 0;
  38608. for (u = 0; u < lu; u++) {
  38609. uvs[u + lu] = uvs[u];
  38610. }
  38611. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38612. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38613. u = 0;
  38614. for (i = 0; i < lu / 2; i++) {
  38615. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38616. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38617. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38618. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38619. u += 2;
  38620. }
  38621. break;
  38622. }
  38623. };
  38624. /**
  38625. * Applies VertexData created from the imported parameters to the geometry
  38626. * @param parsedVertexData the parsed data from an imported file
  38627. * @param geometry the geometry to apply the VertexData to
  38628. */
  38629. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38630. var vertexData = new VertexData();
  38631. // positions
  38632. var positions = parsedVertexData.positions;
  38633. if (positions) {
  38634. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38635. }
  38636. // normals
  38637. var normals = parsedVertexData.normals;
  38638. if (normals) {
  38639. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38640. }
  38641. // tangents
  38642. var tangents = parsedVertexData.tangents;
  38643. if (tangents) {
  38644. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38645. }
  38646. // uvs
  38647. var uvs = parsedVertexData.uvs;
  38648. if (uvs) {
  38649. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38650. }
  38651. // uv2s
  38652. var uv2s = parsedVertexData.uv2s;
  38653. if (uv2s) {
  38654. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38655. }
  38656. // uv3s
  38657. var uv3s = parsedVertexData.uv3s;
  38658. if (uv3s) {
  38659. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38660. }
  38661. // uv4s
  38662. var uv4s = parsedVertexData.uv4s;
  38663. if (uv4s) {
  38664. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38665. }
  38666. // uv5s
  38667. var uv5s = parsedVertexData.uv5s;
  38668. if (uv5s) {
  38669. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38670. }
  38671. // uv6s
  38672. var uv6s = parsedVertexData.uv6s;
  38673. if (uv6s) {
  38674. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38675. }
  38676. // colors
  38677. var colors = parsedVertexData.colors;
  38678. if (colors) {
  38679. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38680. }
  38681. // matricesIndices
  38682. var matricesIndices = parsedVertexData.matricesIndices;
  38683. if (matricesIndices) {
  38684. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38685. }
  38686. // matricesWeights
  38687. var matricesWeights = parsedVertexData.matricesWeights;
  38688. if (matricesWeights) {
  38689. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38690. }
  38691. // indices
  38692. var indices = parsedVertexData.indices;
  38693. if (indices) {
  38694. vertexData.indices = indices;
  38695. }
  38696. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38697. };
  38698. return VertexData;
  38699. }());
  38700. BABYLON.VertexData = VertexData;
  38701. })(BABYLON || (BABYLON = {}));
  38702. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38703. var BABYLON;
  38704. (function (BABYLON) {
  38705. /**
  38706. * Class used to store geometry data (vertex buffers + index buffer)
  38707. */
  38708. var Geometry = /** @class */ (function () {
  38709. /**
  38710. * Creates a new geometry
  38711. * @param id defines the unique ID
  38712. * @param scene defines the hosting scene
  38713. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38714. * @param updatable defines if geometry must be updatable (false by default)
  38715. * @param mesh defines the mesh that will be associated with the geometry
  38716. */
  38717. function Geometry(id, scene, vertexData, updatable, mesh) {
  38718. if (updatable === void 0) { updatable = false; }
  38719. if (mesh === void 0) { mesh = null; }
  38720. /**
  38721. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38722. */
  38723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38724. this._totalVertices = 0;
  38725. this._isDisposed = false;
  38726. this._indexBufferIsUpdatable = false;
  38727. this.id = id;
  38728. this._engine = scene.getEngine();
  38729. this._meshes = [];
  38730. this._scene = scene;
  38731. //Init vertex buffer cache
  38732. this._vertexBuffers = {};
  38733. this._indices = [];
  38734. this._updatable = updatable;
  38735. // vertexData
  38736. if (vertexData) {
  38737. this.setAllVerticesData(vertexData, updatable);
  38738. }
  38739. else {
  38740. this._totalVertices = 0;
  38741. this._indices = [];
  38742. }
  38743. if (this._engine.getCaps().vertexArrayObject) {
  38744. this._vertexArrayObjects = {};
  38745. }
  38746. // applyToMesh
  38747. if (mesh) {
  38748. if (mesh.getClassName() === "LinesMesh") {
  38749. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38750. this._updateExtend();
  38751. }
  38752. this.applyToMesh(mesh);
  38753. mesh.computeWorldMatrix(true);
  38754. }
  38755. }
  38756. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38757. /**
  38758. * 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
  38759. */
  38760. get: function () {
  38761. return this._boundingBias;
  38762. },
  38763. /**
  38764. * 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
  38765. */
  38766. set: function (value) {
  38767. if (this._boundingBias && this._boundingBias.equals(value)) {
  38768. return;
  38769. }
  38770. this._boundingBias = value.clone();
  38771. this._updateBoundingInfo(true, null);
  38772. },
  38773. enumerable: true,
  38774. configurable: true
  38775. });
  38776. /**
  38777. * Static function used to attach a new empty geometry to a mesh
  38778. * @param mesh defines the mesh to attach the geometry to
  38779. * @returns the new {BABYLON.Geometry}
  38780. */
  38781. Geometry.CreateGeometryForMesh = function (mesh) {
  38782. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38783. geometry.applyToMesh(mesh);
  38784. return geometry;
  38785. };
  38786. Object.defineProperty(Geometry.prototype, "extend", {
  38787. /**
  38788. * Gets the current extend of the geometry
  38789. */
  38790. get: function () {
  38791. return this._extend;
  38792. },
  38793. enumerable: true,
  38794. configurable: true
  38795. });
  38796. /**
  38797. * Gets the hosting scene
  38798. * @returns the hosting {BABYLON.Scene}
  38799. */
  38800. Geometry.prototype.getScene = function () {
  38801. return this._scene;
  38802. };
  38803. /**
  38804. * Gets the hosting engine
  38805. * @returns the hosting {BABYLON.Engine}
  38806. */
  38807. Geometry.prototype.getEngine = function () {
  38808. return this._engine;
  38809. };
  38810. /**
  38811. * Defines if the geometry is ready to use
  38812. * @returns true if the geometry is ready to be used
  38813. */
  38814. Geometry.prototype.isReady = function () {
  38815. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38816. };
  38817. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38818. /**
  38819. * Gets a value indicating that the geometry should not be serialized
  38820. */
  38821. get: function () {
  38822. for (var index = 0; index < this._meshes.length; index++) {
  38823. if (!this._meshes[index].doNotSerialize) {
  38824. return false;
  38825. }
  38826. }
  38827. return true;
  38828. },
  38829. enumerable: true,
  38830. configurable: true
  38831. });
  38832. /** @hidden */
  38833. Geometry.prototype._rebuild = function () {
  38834. if (this._vertexArrayObjects) {
  38835. this._vertexArrayObjects = {};
  38836. }
  38837. // Index buffer
  38838. if (this._meshes.length !== 0 && this._indices) {
  38839. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38840. }
  38841. // Vertex buffers
  38842. for (var key in this._vertexBuffers) {
  38843. var vertexBuffer = this._vertexBuffers[key];
  38844. vertexBuffer._rebuild();
  38845. }
  38846. };
  38847. /**
  38848. * Affects all geometry data in one call
  38849. * @param vertexData defines the geometry data
  38850. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38851. */
  38852. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38853. vertexData.applyToGeometry(this, updatable);
  38854. this.notifyUpdate();
  38855. };
  38856. /**
  38857. * Set specific vertex data
  38858. * @param kind defines the data kind (Position, normal, etc...)
  38859. * @param data defines the vertex data to use
  38860. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38861. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38862. */
  38863. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38864. if (updatable === void 0) { updatable = false; }
  38865. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38866. this.setVerticesBuffer(buffer);
  38867. };
  38868. /**
  38869. * Removes a specific vertex data
  38870. * @param kind defines the data kind (Position, normal, etc...)
  38871. */
  38872. Geometry.prototype.removeVerticesData = function (kind) {
  38873. if (this._vertexBuffers[kind]) {
  38874. this._vertexBuffers[kind].dispose();
  38875. delete this._vertexBuffers[kind];
  38876. }
  38877. };
  38878. /**
  38879. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38880. * @param buffer defines the vertex buffer to use
  38881. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38882. */
  38883. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38884. if (totalVertices === void 0) { totalVertices = null; }
  38885. var kind = buffer.getKind();
  38886. if (this._vertexBuffers[kind]) {
  38887. this._vertexBuffers[kind].dispose();
  38888. }
  38889. this._vertexBuffers[kind] = buffer;
  38890. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38891. var data = buffer.getData();
  38892. if (totalVertices != null) {
  38893. this._totalVertices = totalVertices;
  38894. }
  38895. else {
  38896. if (data != null) {
  38897. this._totalVertices = data.length / (buffer.byteStride / 4);
  38898. }
  38899. }
  38900. this._updateExtend(data);
  38901. this._resetPointsArrayCache();
  38902. var meshes = this._meshes;
  38903. var numOfMeshes = meshes.length;
  38904. for (var index = 0; index < numOfMeshes; index++) {
  38905. var mesh = meshes[index];
  38906. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38907. mesh._createGlobalSubMesh(false);
  38908. mesh.computeWorldMatrix(true);
  38909. }
  38910. }
  38911. this.notifyUpdate(kind);
  38912. if (this._vertexArrayObjects) {
  38913. this._disposeVertexArrayObjects();
  38914. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38915. }
  38916. };
  38917. /**
  38918. * Update a specific vertex buffer
  38919. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38920. * It will do nothing if the buffer is not updatable
  38921. * @param kind defines the data kind (Position, normal, etc...)
  38922. * @param data defines the data to use
  38923. * @param offset defines the offset in the target buffer where to store the data
  38924. * @param useBytes set to true if the offset is in bytes
  38925. */
  38926. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38927. if (useBytes === void 0) { useBytes = false; }
  38928. var vertexBuffer = this.getVertexBuffer(kind);
  38929. if (!vertexBuffer) {
  38930. return;
  38931. }
  38932. vertexBuffer.updateDirectly(data, offset, useBytes);
  38933. this.notifyUpdate(kind);
  38934. };
  38935. /**
  38936. * Update a specific vertex buffer
  38937. * This function will create a new buffer if the current one is not updatable
  38938. * @param kind defines the data kind (Position, normal, etc...)
  38939. * @param data defines the data to use
  38940. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38941. */
  38942. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38943. if (updateExtends === void 0) { updateExtends = false; }
  38944. var vertexBuffer = this.getVertexBuffer(kind);
  38945. if (!vertexBuffer) {
  38946. return;
  38947. }
  38948. vertexBuffer.update(data);
  38949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38950. this._updateBoundingInfo(updateExtends, data);
  38951. }
  38952. this.notifyUpdate(kind);
  38953. };
  38954. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38955. if (updateExtends) {
  38956. this._updateExtend(data);
  38957. }
  38958. var meshes = this._meshes;
  38959. var numOfMeshes = meshes.length;
  38960. this._resetPointsArrayCache();
  38961. for (var index = 0; index < numOfMeshes; index++) {
  38962. var mesh = meshes[index];
  38963. if (updateExtends) {
  38964. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38965. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38966. var subMesh = mesh.subMeshes[subIndex];
  38967. subMesh.refreshBoundingInfo();
  38968. }
  38969. }
  38970. }
  38971. };
  38972. /** @hidden */
  38973. Geometry.prototype._bind = function (effect, indexToBind) {
  38974. if (!effect) {
  38975. return;
  38976. }
  38977. if (indexToBind === undefined) {
  38978. indexToBind = this._indexBuffer;
  38979. }
  38980. var vbs = this.getVertexBuffers();
  38981. if (!vbs) {
  38982. return;
  38983. }
  38984. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38985. this._engine.bindBuffers(vbs, indexToBind, effect);
  38986. return;
  38987. }
  38988. // Using VAO
  38989. if (!this._vertexArrayObjects[effect.key]) {
  38990. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38991. }
  38992. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38993. };
  38994. /**
  38995. * Gets total number of vertices
  38996. * @returns the total number of vertices
  38997. */
  38998. Geometry.prototype.getTotalVertices = function () {
  38999. if (!this.isReady()) {
  39000. return 0;
  39001. }
  39002. return this._totalVertices;
  39003. };
  39004. /**
  39005. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39006. * @param kind defines the data kind (Position, normal, etc...)
  39007. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39008. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39009. * @returns a float array containing vertex data
  39010. */
  39011. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39012. var vertexBuffer = this.getVertexBuffer(kind);
  39013. if (!vertexBuffer) {
  39014. return null;
  39015. }
  39016. var data = vertexBuffer.getData();
  39017. if (!data) {
  39018. return null;
  39019. }
  39020. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39021. var count = this._totalVertices * vertexBuffer.getSize();
  39022. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39023. var copy_1 = new Array(count);
  39024. vertexBuffer.forEach(count, function (value, index) {
  39025. copy_1[index] = value;
  39026. });
  39027. return copy_1;
  39028. }
  39029. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39030. if (data instanceof Array) {
  39031. var offset = vertexBuffer.byteOffset / 4;
  39032. return BABYLON.Tools.Slice(data, offset, offset + count);
  39033. }
  39034. else if (data instanceof ArrayBuffer) {
  39035. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39036. }
  39037. else {
  39038. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39039. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39040. var result = new Float32Array(count);
  39041. var source = new Float32Array(data.buffer, offset, count);
  39042. result.set(source);
  39043. return result;
  39044. }
  39045. return new Float32Array(data.buffer, offset, count);
  39046. }
  39047. }
  39048. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39049. return BABYLON.Tools.Slice(data);
  39050. }
  39051. return data;
  39052. };
  39053. /**
  39054. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39055. * @param kind defines the data kind (Position, normal, etc...)
  39056. * @returns true if the vertex buffer with the specified kind is updatable
  39057. */
  39058. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39059. var vb = this._vertexBuffers[kind];
  39060. if (!vb) {
  39061. return false;
  39062. }
  39063. return vb.isUpdatable();
  39064. };
  39065. /**
  39066. * Gets a specific vertex buffer
  39067. * @param kind defines the data kind (Position, normal, etc...)
  39068. * @returns a {BABYLON.VertexBuffer}
  39069. */
  39070. Geometry.prototype.getVertexBuffer = function (kind) {
  39071. if (!this.isReady()) {
  39072. return null;
  39073. }
  39074. return this._vertexBuffers[kind];
  39075. };
  39076. /**
  39077. * Returns all vertex buffers
  39078. * @return an object holding all vertex buffers indexed by kind
  39079. */
  39080. Geometry.prototype.getVertexBuffers = function () {
  39081. if (!this.isReady()) {
  39082. return null;
  39083. }
  39084. return this._vertexBuffers;
  39085. };
  39086. /**
  39087. * Gets a boolean indicating if specific vertex buffer is present
  39088. * @param kind defines the data kind (Position, normal, etc...)
  39089. * @returns true if data is present
  39090. */
  39091. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39092. if (!this._vertexBuffers) {
  39093. if (this._delayInfo) {
  39094. return this._delayInfo.indexOf(kind) !== -1;
  39095. }
  39096. return false;
  39097. }
  39098. return this._vertexBuffers[kind] !== undefined;
  39099. };
  39100. /**
  39101. * Gets a list of all attached data kinds (Position, normal, etc...)
  39102. * @returns a list of string containing all kinds
  39103. */
  39104. Geometry.prototype.getVerticesDataKinds = function () {
  39105. var result = [];
  39106. var kind;
  39107. if (!this._vertexBuffers && this._delayInfo) {
  39108. for (kind in this._delayInfo) {
  39109. result.push(kind);
  39110. }
  39111. }
  39112. else {
  39113. for (kind in this._vertexBuffers) {
  39114. result.push(kind);
  39115. }
  39116. }
  39117. return result;
  39118. };
  39119. /**
  39120. * Update index buffer
  39121. * @param indices defines the indices to store in the index buffer
  39122. * @param offset defines the offset in the target buffer where to store the data
  39123. */
  39124. Geometry.prototype.updateIndices = function (indices, offset) {
  39125. if (!this._indexBuffer) {
  39126. return;
  39127. }
  39128. if (!this._indexBufferIsUpdatable) {
  39129. this.setIndices(indices, null, true);
  39130. }
  39131. else {
  39132. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39133. }
  39134. };
  39135. /**
  39136. * Creates a new index buffer
  39137. * @param indices defines the indices to store in the index buffer
  39138. * @param totalVertices defines the total number of vertices (could be null)
  39139. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39140. */
  39141. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39142. if (totalVertices === void 0) { totalVertices = null; }
  39143. if (updatable === void 0) { updatable = false; }
  39144. if (this._indexBuffer) {
  39145. this._engine._releaseBuffer(this._indexBuffer);
  39146. }
  39147. this._disposeVertexArrayObjects();
  39148. this._indices = indices;
  39149. this._indexBufferIsUpdatable = updatable;
  39150. if (this._meshes.length !== 0 && this._indices) {
  39151. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39152. }
  39153. if (totalVertices != undefined) { // including null and undefined
  39154. this._totalVertices = totalVertices;
  39155. }
  39156. var meshes = this._meshes;
  39157. var numOfMeshes = meshes.length;
  39158. for (var index = 0; index < numOfMeshes; index++) {
  39159. meshes[index]._createGlobalSubMesh(true);
  39160. }
  39161. this.notifyUpdate();
  39162. };
  39163. /**
  39164. * Return the total number of indices
  39165. * @returns the total number of indices
  39166. */
  39167. Geometry.prototype.getTotalIndices = function () {
  39168. if (!this.isReady()) {
  39169. return 0;
  39170. }
  39171. return this._indices.length;
  39172. };
  39173. /**
  39174. * Gets the index buffer array
  39175. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39176. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39177. * @returns the index buffer array
  39178. */
  39179. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39180. if (!this.isReady()) {
  39181. return null;
  39182. }
  39183. var orig = this._indices;
  39184. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39185. return orig;
  39186. }
  39187. else {
  39188. var len = orig.length;
  39189. var copy = [];
  39190. for (var i = 0; i < len; i++) {
  39191. copy.push(orig[i]);
  39192. }
  39193. return copy;
  39194. }
  39195. };
  39196. /**
  39197. * Gets the index buffer
  39198. * @return the index buffer
  39199. */
  39200. Geometry.prototype.getIndexBuffer = function () {
  39201. if (!this.isReady()) {
  39202. return null;
  39203. }
  39204. return this._indexBuffer;
  39205. };
  39206. /** @hidden */
  39207. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39208. if (effect === void 0) { effect = null; }
  39209. if (!effect || !this._vertexArrayObjects) {
  39210. return;
  39211. }
  39212. if (this._vertexArrayObjects[effect.key]) {
  39213. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39214. delete this._vertexArrayObjects[effect.key];
  39215. }
  39216. };
  39217. /**
  39218. * Release the associated resources for a specific mesh
  39219. * @param mesh defines the source mesh
  39220. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39221. */
  39222. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39223. var meshes = this._meshes;
  39224. var index = meshes.indexOf(mesh);
  39225. if (index === -1) {
  39226. return;
  39227. }
  39228. meshes.splice(index, 1);
  39229. mesh._geometry = null;
  39230. if (meshes.length === 0 && shouldDispose) {
  39231. this.dispose();
  39232. }
  39233. };
  39234. /**
  39235. * Apply current geometry to a given mesh
  39236. * @param mesh defines the mesh to apply geometry to
  39237. */
  39238. Geometry.prototype.applyToMesh = function (mesh) {
  39239. if (mesh._geometry === this) {
  39240. return;
  39241. }
  39242. var previousGeometry = mesh._geometry;
  39243. if (previousGeometry) {
  39244. previousGeometry.releaseForMesh(mesh);
  39245. }
  39246. var meshes = this._meshes;
  39247. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39248. mesh._geometry = this;
  39249. this._scene.pushGeometry(this);
  39250. meshes.push(mesh);
  39251. if (this.isReady()) {
  39252. this._applyToMesh(mesh);
  39253. }
  39254. else {
  39255. mesh._boundingInfo = this._boundingInfo;
  39256. }
  39257. };
  39258. Geometry.prototype._updateExtend = function (data) {
  39259. if (data === void 0) { data = null; }
  39260. if (!data) {
  39261. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39262. }
  39263. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39264. };
  39265. Geometry.prototype._applyToMesh = function (mesh) {
  39266. var numOfMeshes = this._meshes.length;
  39267. // vertexBuffers
  39268. for (var kind in this._vertexBuffers) {
  39269. if (numOfMeshes === 1) {
  39270. this._vertexBuffers[kind].create();
  39271. }
  39272. var buffer = this._vertexBuffers[kind].getBuffer();
  39273. if (buffer)
  39274. buffer.references = numOfMeshes;
  39275. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39276. if (!this._extend) {
  39277. this._updateExtend();
  39278. }
  39279. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39280. mesh._createGlobalSubMesh(false);
  39281. //bounding info was just created again, world matrix should be applied again.
  39282. mesh._updateBoundingInfo();
  39283. }
  39284. }
  39285. // indexBuffer
  39286. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39287. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39288. }
  39289. if (this._indexBuffer) {
  39290. this._indexBuffer.references = numOfMeshes;
  39291. }
  39292. };
  39293. Geometry.prototype.notifyUpdate = function (kind) {
  39294. if (this.onGeometryUpdated) {
  39295. this.onGeometryUpdated(this, kind);
  39296. }
  39297. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39298. var mesh = _a[_i];
  39299. mesh._markSubMeshesAsAttributesDirty();
  39300. }
  39301. };
  39302. /**
  39303. * Load the geometry if it was flagged as delay loaded
  39304. * @param scene defines the hosting scene
  39305. * @param onLoaded defines a callback called when the geometry is loaded
  39306. */
  39307. Geometry.prototype.load = function (scene, onLoaded) {
  39308. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39309. return;
  39310. }
  39311. if (this.isReady()) {
  39312. if (onLoaded) {
  39313. onLoaded();
  39314. }
  39315. return;
  39316. }
  39317. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39318. this._queueLoad(scene, onLoaded);
  39319. };
  39320. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39321. var _this = this;
  39322. if (!this.delayLoadingFile) {
  39323. return;
  39324. }
  39325. scene._addPendingData(this);
  39326. scene._loadFile(this.delayLoadingFile, function (data) {
  39327. if (!_this._delayLoadingFunction) {
  39328. return;
  39329. }
  39330. _this._delayLoadingFunction(JSON.parse(data), _this);
  39331. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39332. _this._delayInfo = [];
  39333. scene._removePendingData(_this);
  39334. var meshes = _this._meshes;
  39335. var numOfMeshes = meshes.length;
  39336. for (var index = 0; index < numOfMeshes; index++) {
  39337. _this._applyToMesh(meshes[index]);
  39338. }
  39339. if (onLoaded) {
  39340. onLoaded();
  39341. }
  39342. }, undefined, true);
  39343. };
  39344. /**
  39345. * Invert the geometry to move from a right handed system to a left handed one.
  39346. */
  39347. Geometry.prototype.toLeftHanded = function () {
  39348. // Flip faces
  39349. var tIndices = this.getIndices(false);
  39350. if (tIndices != null && tIndices.length > 0) {
  39351. for (var i = 0; i < tIndices.length; i += 3) {
  39352. var tTemp = tIndices[i + 0];
  39353. tIndices[i + 0] = tIndices[i + 2];
  39354. tIndices[i + 2] = tTemp;
  39355. }
  39356. this.setIndices(tIndices);
  39357. }
  39358. // Negate position.z
  39359. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39360. if (tPositions != null && tPositions.length > 0) {
  39361. for (var i = 0; i < tPositions.length; i += 3) {
  39362. tPositions[i + 2] = -tPositions[i + 2];
  39363. }
  39364. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39365. }
  39366. // Negate normal.z
  39367. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39368. if (tNormals != null && tNormals.length > 0) {
  39369. for (var i = 0; i < tNormals.length; i += 3) {
  39370. tNormals[i + 2] = -tNormals[i + 2];
  39371. }
  39372. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39373. }
  39374. };
  39375. // Cache
  39376. /** @hidden */
  39377. Geometry.prototype._resetPointsArrayCache = function () {
  39378. this._positions = null;
  39379. };
  39380. /** @hidden */
  39381. Geometry.prototype._generatePointsArray = function () {
  39382. if (this._positions)
  39383. return true;
  39384. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39385. if (!data || data.length === 0) {
  39386. return false;
  39387. }
  39388. this._positions = [];
  39389. for (var index = 0; index < data.length; index += 3) {
  39390. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39391. }
  39392. return true;
  39393. };
  39394. /**
  39395. * Gets a value indicating if the geometry is disposed
  39396. * @returns true if the geometry was disposed
  39397. */
  39398. Geometry.prototype.isDisposed = function () {
  39399. return this._isDisposed;
  39400. };
  39401. Geometry.prototype._disposeVertexArrayObjects = function () {
  39402. if (this._vertexArrayObjects) {
  39403. for (var kind in this._vertexArrayObjects) {
  39404. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39405. }
  39406. this._vertexArrayObjects = {};
  39407. }
  39408. };
  39409. /**
  39410. * Free all associated resources
  39411. */
  39412. Geometry.prototype.dispose = function () {
  39413. var meshes = this._meshes;
  39414. var numOfMeshes = meshes.length;
  39415. var index;
  39416. for (index = 0; index < numOfMeshes; index++) {
  39417. this.releaseForMesh(meshes[index]);
  39418. }
  39419. this._meshes = [];
  39420. this._disposeVertexArrayObjects();
  39421. for (var kind in this._vertexBuffers) {
  39422. this._vertexBuffers[kind].dispose();
  39423. }
  39424. this._vertexBuffers = {};
  39425. this._totalVertices = 0;
  39426. if (this._indexBuffer) {
  39427. this._engine._releaseBuffer(this._indexBuffer);
  39428. }
  39429. this._indexBuffer = null;
  39430. this._indices = [];
  39431. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39432. this.delayLoadingFile = null;
  39433. this._delayLoadingFunction = null;
  39434. this._delayInfo = [];
  39435. this._boundingInfo = null;
  39436. this._scene.removeGeometry(this);
  39437. this._isDisposed = true;
  39438. };
  39439. /**
  39440. * Clone the current geometry into a new geometry
  39441. * @param id defines the unique ID of the new geometry
  39442. * @returns a new geometry object
  39443. */
  39444. Geometry.prototype.copy = function (id) {
  39445. var vertexData = new BABYLON.VertexData();
  39446. vertexData.indices = [];
  39447. var indices = this.getIndices();
  39448. if (indices) {
  39449. for (var index = 0; index < indices.length; index++) {
  39450. vertexData.indices.push(indices[index]);
  39451. }
  39452. }
  39453. var updatable = false;
  39454. var stopChecking = false;
  39455. var kind;
  39456. for (kind in this._vertexBuffers) {
  39457. // using slice() to make a copy of the array and not just reference it
  39458. var data = this.getVerticesData(kind);
  39459. if (data instanceof Float32Array) {
  39460. vertexData.set(new Float32Array(data), kind);
  39461. }
  39462. else {
  39463. vertexData.set(data.slice(0), kind);
  39464. }
  39465. if (!stopChecking) {
  39466. var vb = this.getVertexBuffer(kind);
  39467. if (vb) {
  39468. updatable = vb.isUpdatable();
  39469. stopChecking = !updatable;
  39470. }
  39471. }
  39472. }
  39473. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39474. geometry.delayLoadState = this.delayLoadState;
  39475. geometry.delayLoadingFile = this.delayLoadingFile;
  39476. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39477. for (kind in this._delayInfo) {
  39478. geometry._delayInfo = geometry._delayInfo || [];
  39479. geometry._delayInfo.push(kind);
  39480. }
  39481. // Bounding info
  39482. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39483. return geometry;
  39484. };
  39485. /**
  39486. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39487. * @return a JSON representation of the current geometry data (without the vertices data)
  39488. */
  39489. Geometry.prototype.serialize = function () {
  39490. var serializationObject = {};
  39491. serializationObject.id = this.id;
  39492. serializationObject.updatable = this._updatable;
  39493. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39494. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39495. }
  39496. return serializationObject;
  39497. };
  39498. Geometry.prototype.toNumberArray = function (origin) {
  39499. if (Array.isArray(origin)) {
  39500. return origin;
  39501. }
  39502. else {
  39503. return Array.prototype.slice.call(origin);
  39504. }
  39505. };
  39506. /**
  39507. * Serialize all vertices data into a JSON oject
  39508. * @returns a JSON representation of the current geometry data
  39509. */
  39510. Geometry.prototype.serializeVerticeData = function () {
  39511. var serializationObject = this.serialize();
  39512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39513. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39514. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39515. serializationObject.positions._updatable = true;
  39516. }
  39517. }
  39518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39519. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39520. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39521. serializationObject.normals._updatable = true;
  39522. }
  39523. }
  39524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39525. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39526. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39527. serializationObject.tangets._updatable = true;
  39528. }
  39529. }
  39530. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39531. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39532. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39533. serializationObject.uvs._updatable = true;
  39534. }
  39535. }
  39536. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39537. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39538. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39539. serializationObject.uv2s._updatable = true;
  39540. }
  39541. }
  39542. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39543. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39544. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39545. serializationObject.uv3s._updatable = true;
  39546. }
  39547. }
  39548. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39549. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39550. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39551. serializationObject.uv4s._updatable = true;
  39552. }
  39553. }
  39554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39555. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39556. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39557. serializationObject.uv5s._updatable = true;
  39558. }
  39559. }
  39560. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39561. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39562. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39563. serializationObject.uv6s._updatable = true;
  39564. }
  39565. }
  39566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39567. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39568. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39569. serializationObject.colors._updatable = true;
  39570. }
  39571. }
  39572. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39573. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39574. serializationObject.matricesIndices._isExpanded = true;
  39575. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39576. serializationObject.matricesIndices._updatable = true;
  39577. }
  39578. }
  39579. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39580. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39581. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39582. serializationObject.matricesWeights._updatable = true;
  39583. }
  39584. }
  39585. serializationObject.indices = this.toNumberArray(this.getIndices());
  39586. return serializationObject;
  39587. };
  39588. // Statics
  39589. /**
  39590. * Extracts a clone of a mesh geometry
  39591. * @param mesh defines the source mesh
  39592. * @param id defines the unique ID of the new geometry object
  39593. * @returns the new geometry object
  39594. */
  39595. Geometry.ExtractFromMesh = function (mesh, id) {
  39596. var geometry = mesh._geometry;
  39597. if (!geometry) {
  39598. return null;
  39599. }
  39600. return geometry.copy(id);
  39601. };
  39602. /**
  39603. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39604. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39605. * Be aware Math.random() could cause collisions, but:
  39606. * "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"
  39607. * @returns a string containing a new GUID
  39608. */
  39609. Geometry.RandomId = function () {
  39610. return BABYLON.Tools.RandomId();
  39611. };
  39612. /** @hidden */
  39613. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39614. var scene = mesh.getScene();
  39615. // Geometry
  39616. var geometryId = parsedGeometry.geometryId;
  39617. if (geometryId) {
  39618. var geometry = scene.getGeometryByID(geometryId);
  39619. if (geometry) {
  39620. geometry.applyToMesh(mesh);
  39621. }
  39622. }
  39623. else if (parsedGeometry instanceof ArrayBuffer) {
  39624. var binaryInfo = mesh._binaryInfo;
  39625. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39626. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39627. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39628. }
  39629. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39630. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39631. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39632. }
  39633. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39634. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39635. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39636. }
  39637. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39638. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39639. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39640. }
  39641. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39642. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39643. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39644. }
  39645. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39646. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39647. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39648. }
  39649. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39650. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39651. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39652. }
  39653. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39654. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39655. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39656. }
  39657. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39658. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39659. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39660. }
  39661. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39662. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39663. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39664. }
  39665. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39666. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39667. var floatIndices = [];
  39668. for (var i = 0; i < matricesIndicesData.length; i++) {
  39669. var index = matricesIndicesData[i];
  39670. floatIndices.push(index & 0x000000FF);
  39671. floatIndices.push((index & 0x0000FF00) >> 8);
  39672. floatIndices.push((index & 0x00FF0000) >> 16);
  39673. floatIndices.push(index >> 24);
  39674. }
  39675. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39676. }
  39677. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39678. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39680. }
  39681. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39682. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39683. mesh.setIndices(indicesData, null);
  39684. }
  39685. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39686. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39687. mesh.subMeshes = [];
  39688. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39689. var materialIndex = subMeshesData[(i * 5) + 0];
  39690. var verticesStart = subMeshesData[(i * 5) + 1];
  39691. var verticesCount = subMeshesData[(i * 5) + 2];
  39692. var indexStart = subMeshesData[(i * 5) + 3];
  39693. var indexCount = subMeshesData[(i * 5) + 4];
  39694. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39695. }
  39696. }
  39697. }
  39698. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39699. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39700. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39701. if (parsedGeometry.tangents) {
  39702. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39703. }
  39704. if (parsedGeometry.uvs) {
  39705. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39706. }
  39707. if (parsedGeometry.uvs2) {
  39708. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39709. }
  39710. if (parsedGeometry.uvs3) {
  39711. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39712. }
  39713. if (parsedGeometry.uvs4) {
  39714. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39715. }
  39716. if (parsedGeometry.uvs5) {
  39717. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39718. }
  39719. if (parsedGeometry.uvs6) {
  39720. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39721. }
  39722. if (parsedGeometry.colors) {
  39723. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39724. }
  39725. if (parsedGeometry.matricesIndices) {
  39726. if (!parsedGeometry.matricesIndices._isExpanded) {
  39727. var floatIndices = [];
  39728. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39729. var matricesIndex = parsedGeometry.matricesIndices[i];
  39730. floatIndices.push(matricesIndex & 0x000000FF);
  39731. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39732. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39733. floatIndices.push(matricesIndex >> 24);
  39734. }
  39735. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39736. }
  39737. else {
  39738. delete parsedGeometry.matricesIndices._isExpanded;
  39739. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39740. }
  39741. }
  39742. if (parsedGeometry.matricesIndicesExtra) {
  39743. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39744. var floatIndices = [];
  39745. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39746. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39747. floatIndices.push(matricesIndex & 0x000000FF);
  39748. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39749. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39750. floatIndices.push(matricesIndex >> 24);
  39751. }
  39752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39753. }
  39754. else {
  39755. delete parsedGeometry.matricesIndices._isExpanded;
  39756. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39757. }
  39758. }
  39759. if (parsedGeometry.matricesWeights) {
  39760. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39761. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39762. }
  39763. if (parsedGeometry.matricesWeightsExtra) {
  39764. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39765. }
  39766. mesh.setIndices(parsedGeometry.indices, null);
  39767. }
  39768. // SubMeshes
  39769. if (parsedGeometry.subMeshes) {
  39770. mesh.subMeshes = [];
  39771. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39772. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39773. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39774. }
  39775. }
  39776. // Flat shading
  39777. if (mesh._shouldGenerateFlatShading) {
  39778. mesh.convertToFlatShadedMesh();
  39779. delete mesh._shouldGenerateFlatShading;
  39780. }
  39781. // Update
  39782. mesh.computeWorldMatrix(true);
  39783. // Octree
  39784. var sceneOctree = scene.selectionOctree;
  39785. if (sceneOctree !== undefined && sceneOctree !== null) {
  39786. sceneOctree.addMesh(mesh);
  39787. }
  39788. };
  39789. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39790. var epsilon = 1e-3;
  39791. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39792. return;
  39793. }
  39794. var noInfluenceBoneIndex = 0.0;
  39795. if (parsedGeometry.skeletonId > -1) {
  39796. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39797. if (!skeleton) {
  39798. return;
  39799. }
  39800. noInfluenceBoneIndex = skeleton.bones.length;
  39801. }
  39802. else {
  39803. return;
  39804. }
  39805. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39806. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39807. var matricesWeights = parsedGeometry.matricesWeights;
  39808. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39809. var influencers = parsedGeometry.numBoneInfluencer;
  39810. var size = matricesWeights.length;
  39811. for (var i = 0; i < size; i += 4) {
  39812. var weight = 0.0;
  39813. var firstZeroWeight = -1;
  39814. for (var j = 0; j < 4; j++) {
  39815. var w = matricesWeights[i + j];
  39816. weight += w;
  39817. if (w < epsilon && firstZeroWeight < 0) {
  39818. firstZeroWeight = j;
  39819. }
  39820. }
  39821. if (matricesWeightsExtra) {
  39822. for (var j = 0; j < 4; j++) {
  39823. var w = matricesWeightsExtra[i + j];
  39824. weight += w;
  39825. if (w < epsilon && firstZeroWeight < 0) {
  39826. firstZeroWeight = j + 4;
  39827. }
  39828. }
  39829. }
  39830. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39831. firstZeroWeight = influencers - 1;
  39832. }
  39833. if (weight > epsilon) {
  39834. var mweight = 1.0 / weight;
  39835. for (var j = 0; j < 4; j++) {
  39836. matricesWeights[i + j] *= mweight;
  39837. }
  39838. if (matricesWeightsExtra) {
  39839. for (var j = 0; j < 4; j++) {
  39840. matricesWeightsExtra[i + j] *= mweight;
  39841. }
  39842. }
  39843. }
  39844. else {
  39845. if (firstZeroWeight >= 4) {
  39846. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39847. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39848. }
  39849. else {
  39850. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39851. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39852. }
  39853. }
  39854. }
  39855. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39856. if (parsedGeometry.matricesWeightsExtra) {
  39857. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39858. }
  39859. };
  39860. /**
  39861. * Create a new geometry from persisted data (Using .babylon file format)
  39862. * @param parsedVertexData defines the persisted data
  39863. * @param scene defines the hosting scene
  39864. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39865. * @returns the new geometry object
  39866. */
  39867. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39868. if (scene.getGeometryByID(parsedVertexData.id)) {
  39869. return null; // null since geometry could be something else than a box...
  39870. }
  39871. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39872. if (BABYLON.Tags) {
  39873. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39874. }
  39875. if (parsedVertexData.delayLoadingFile) {
  39876. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39877. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39878. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39879. geometry._delayInfo = [];
  39880. if (parsedVertexData.hasUVs) {
  39881. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39882. }
  39883. if (parsedVertexData.hasUVs2) {
  39884. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39885. }
  39886. if (parsedVertexData.hasUVs3) {
  39887. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39888. }
  39889. if (parsedVertexData.hasUVs4) {
  39890. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39891. }
  39892. if (parsedVertexData.hasUVs5) {
  39893. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39894. }
  39895. if (parsedVertexData.hasUVs6) {
  39896. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39897. }
  39898. if (parsedVertexData.hasColors) {
  39899. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39900. }
  39901. if (parsedVertexData.hasMatricesIndices) {
  39902. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39903. }
  39904. if (parsedVertexData.hasMatricesWeights) {
  39905. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39906. }
  39907. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39908. }
  39909. else {
  39910. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39911. }
  39912. scene.pushGeometry(geometry, true);
  39913. return geometry;
  39914. };
  39915. return Geometry;
  39916. }());
  39917. BABYLON.Geometry = Geometry;
  39918. // Primitives
  39919. /// Abstract class
  39920. /**
  39921. * Abstract class used to provide common services for all typed geometries
  39922. * @hidden
  39923. */
  39924. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39925. __extends(_PrimitiveGeometry, _super);
  39926. /**
  39927. * Creates a new typed geometry
  39928. * @param id defines the unique ID of the geometry
  39929. * @param scene defines the hosting scene
  39930. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39931. * @param mesh defines the hosting mesh (can be null)
  39932. */
  39933. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39934. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39935. if (mesh === void 0) { mesh = null; }
  39936. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39937. _this._canBeRegenerated = _canBeRegenerated;
  39938. _this._beingRegenerated = true;
  39939. _this.regenerate();
  39940. _this._beingRegenerated = false;
  39941. return _this;
  39942. }
  39943. /**
  39944. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39945. * @returns true if the geometry can be regenerated
  39946. */
  39947. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39948. return this._canBeRegenerated;
  39949. };
  39950. /**
  39951. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39952. */
  39953. _PrimitiveGeometry.prototype.regenerate = function () {
  39954. if (!this._canBeRegenerated) {
  39955. return;
  39956. }
  39957. this._beingRegenerated = true;
  39958. this.setAllVerticesData(this._regenerateVertexData(), false);
  39959. this._beingRegenerated = false;
  39960. };
  39961. /**
  39962. * Clone the geometry
  39963. * @param id defines the unique ID of the new geometry
  39964. * @returns the new geometry
  39965. */
  39966. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39967. return _super.prototype.copy.call(this, id);
  39968. };
  39969. // overrides
  39970. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39971. if (!this._beingRegenerated) {
  39972. return;
  39973. }
  39974. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39975. };
  39976. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39977. if (!this._beingRegenerated) {
  39978. return;
  39979. }
  39980. _super.prototype.setVerticesData.call(this, kind, data, false);
  39981. };
  39982. // to override
  39983. /** @hidden */
  39984. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39985. throw new Error("Abstract method");
  39986. };
  39987. _PrimitiveGeometry.prototype.copy = function (id) {
  39988. throw new Error("Must be overriden in sub-classes.");
  39989. };
  39990. _PrimitiveGeometry.prototype.serialize = function () {
  39991. var serializationObject = _super.prototype.serialize.call(this);
  39992. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39993. return serializationObject;
  39994. };
  39995. return _PrimitiveGeometry;
  39996. }(Geometry));
  39997. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39998. /**
  39999. * Creates a ribbon geometry
  40000. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40001. */
  40002. var RibbonGeometry = /** @class */ (function (_super) {
  40003. __extends(RibbonGeometry, _super);
  40004. /**
  40005. * Creates a ribbon geometry
  40006. * @param id defines the unique ID of the geometry
  40007. * @param scene defines the hosting scene
  40008. * @param pathArray defines the array of paths to use
  40009. * @param closeArray defines if the last path and the first path must be joined
  40010. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40011. * @param offset defines the offset between points
  40012. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40013. * @param mesh defines the hosting mesh (can be null)
  40014. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40015. */
  40016. function RibbonGeometry(id, scene,
  40017. /**
  40018. * Defines the array of paths to use
  40019. */
  40020. pathArray,
  40021. /**
  40022. * Defines if the last and first points of each path in your pathArray must be joined
  40023. */
  40024. closeArray,
  40025. /**
  40026. * Defines if the last and first points of each path in your pathArray must be joined
  40027. */
  40028. closePath,
  40029. /**
  40030. * Defines the offset between points
  40031. */
  40032. offset, canBeRegenerated, mesh,
  40033. /**
  40034. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40035. */
  40036. side) {
  40037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40039. _this.pathArray = pathArray;
  40040. _this.closeArray = closeArray;
  40041. _this.closePath = closePath;
  40042. _this.offset = offset;
  40043. _this.side = side;
  40044. return _this;
  40045. }
  40046. /** @hidden */
  40047. RibbonGeometry.prototype._regenerateVertexData = function () {
  40048. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40049. };
  40050. RibbonGeometry.prototype.copy = function (id) {
  40051. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40052. };
  40053. return RibbonGeometry;
  40054. }(_PrimitiveGeometry));
  40055. BABYLON.RibbonGeometry = RibbonGeometry;
  40056. /**
  40057. * Creates a box geometry
  40058. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40059. */
  40060. var BoxGeometry = /** @class */ (function (_super) {
  40061. __extends(BoxGeometry, _super);
  40062. /**
  40063. * Creates a box geometry
  40064. * @param id defines the unique ID of the geometry
  40065. * @param scene defines the hosting scene
  40066. * @param size defines the zise of the box (width, height and depth are the same)
  40067. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40068. * @param mesh defines the hosting mesh (can be null)
  40069. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40070. */
  40071. function BoxGeometry(id, scene,
  40072. /**
  40073. * Defines the zise of the box (width, height and depth are the same)
  40074. */
  40075. size, canBeRegenerated, mesh,
  40076. /**
  40077. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40078. */
  40079. side) {
  40080. if (mesh === void 0) { mesh = null; }
  40081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40083. _this.size = size;
  40084. _this.side = side;
  40085. return _this;
  40086. }
  40087. /** @hidden */
  40088. BoxGeometry.prototype._regenerateVertexData = function () {
  40089. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40090. };
  40091. BoxGeometry.prototype.copy = function (id) {
  40092. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40093. };
  40094. BoxGeometry.prototype.serialize = function () {
  40095. var serializationObject = _super.prototype.serialize.call(this);
  40096. serializationObject.size = this.size;
  40097. return serializationObject;
  40098. };
  40099. BoxGeometry.Parse = function (parsedBox, scene) {
  40100. if (scene.getGeometryByID(parsedBox.id)) {
  40101. return null; // null since geometry could be something else than a box...
  40102. }
  40103. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40104. if (BABYLON.Tags) {
  40105. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40106. }
  40107. scene.pushGeometry(box, true);
  40108. return box;
  40109. };
  40110. return BoxGeometry;
  40111. }(_PrimitiveGeometry));
  40112. BABYLON.BoxGeometry = BoxGeometry;
  40113. /**
  40114. * Creates a sphere geometry
  40115. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40116. */
  40117. var SphereGeometry = /** @class */ (function (_super) {
  40118. __extends(SphereGeometry, _super);
  40119. /**
  40120. * Create a new sphere geometry
  40121. * @param id defines the unique ID of the geometry
  40122. * @param scene defines the hosting scene
  40123. * @param segments defines the number of segments to use to create the sphere
  40124. * @param diameter defines the diameter of the sphere
  40125. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40126. * @param mesh defines the hosting mesh (can be null)
  40127. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40128. */
  40129. function SphereGeometry(id, scene,
  40130. /**
  40131. * Defines the number of segments to use to create the sphere
  40132. */
  40133. segments,
  40134. /**
  40135. * Defines the diameter of the sphere
  40136. */
  40137. diameter, canBeRegenerated, mesh,
  40138. /**
  40139. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40140. */
  40141. side) {
  40142. if (mesh === void 0) { mesh = null; }
  40143. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40144. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40145. _this.segments = segments;
  40146. _this.diameter = diameter;
  40147. _this.side = side;
  40148. return _this;
  40149. }
  40150. /** @hidden */
  40151. SphereGeometry.prototype._regenerateVertexData = function () {
  40152. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40153. };
  40154. SphereGeometry.prototype.copy = function (id) {
  40155. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40156. };
  40157. SphereGeometry.prototype.serialize = function () {
  40158. var serializationObject = _super.prototype.serialize.call(this);
  40159. serializationObject.segments = this.segments;
  40160. serializationObject.diameter = this.diameter;
  40161. return serializationObject;
  40162. };
  40163. SphereGeometry.Parse = function (parsedSphere, scene) {
  40164. if (scene.getGeometryByID(parsedSphere.id)) {
  40165. return null; // null since geometry could be something else than a sphere...
  40166. }
  40167. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40168. if (BABYLON.Tags) {
  40169. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40170. }
  40171. scene.pushGeometry(sphere, true);
  40172. return sphere;
  40173. };
  40174. return SphereGeometry;
  40175. }(_PrimitiveGeometry));
  40176. BABYLON.SphereGeometry = SphereGeometry;
  40177. /**
  40178. * Creates a disc geometry
  40179. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40180. */
  40181. var DiscGeometry = /** @class */ (function (_super) {
  40182. __extends(DiscGeometry, _super);
  40183. /**
  40184. * Creates a new disc geometry
  40185. * @param id defines the unique ID of the geometry
  40186. * @param scene defines the hosting scene
  40187. * @param radius defines the radius of the disc
  40188. * @param tessellation defines the tesselation factor to apply to the disc
  40189. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40190. * @param mesh defines the hosting mesh (can be null)
  40191. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40192. */
  40193. function DiscGeometry(id, scene,
  40194. /**
  40195. * Defines the radius of the disc
  40196. */
  40197. radius,
  40198. /**
  40199. * Defines the tesselation factor to apply to the disc
  40200. */
  40201. tessellation, canBeRegenerated, mesh,
  40202. /**
  40203. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40204. */
  40205. side) {
  40206. if (mesh === void 0) { mesh = null; }
  40207. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40208. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40209. _this.radius = radius;
  40210. _this.tessellation = tessellation;
  40211. _this.side = side;
  40212. return _this;
  40213. }
  40214. /** @hidden */
  40215. DiscGeometry.prototype._regenerateVertexData = function () {
  40216. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40217. };
  40218. DiscGeometry.prototype.copy = function (id) {
  40219. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40220. };
  40221. return DiscGeometry;
  40222. }(_PrimitiveGeometry));
  40223. BABYLON.DiscGeometry = DiscGeometry;
  40224. /**
  40225. * Creates a new cylinder geometry
  40226. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40227. */
  40228. var CylinderGeometry = /** @class */ (function (_super) {
  40229. __extends(CylinderGeometry, _super);
  40230. /**
  40231. * Creates a new cylinder geometry
  40232. * @param id defines the unique ID of the geometry
  40233. * @param scene defines the hosting scene
  40234. * @param height defines the height of the cylinder
  40235. * @param diameterTop defines the diameter of the cylinder's top cap
  40236. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40237. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40238. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40239. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40240. * @param mesh defines the hosting mesh (can be null)
  40241. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40242. */
  40243. function CylinderGeometry(id, scene,
  40244. /**
  40245. * Defines the height of the cylinder
  40246. */
  40247. height,
  40248. /**
  40249. * Defines the diameter of the cylinder's top cap
  40250. */
  40251. diameterTop,
  40252. /**
  40253. * Defines the diameter of the cylinder's bottom cap
  40254. */
  40255. diameterBottom,
  40256. /**
  40257. * Defines the tessellation factor to apply to the cylinder
  40258. */
  40259. tessellation,
  40260. /**
  40261. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40262. */
  40263. subdivisions, canBeRegenerated, mesh,
  40264. /**
  40265. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40266. */
  40267. side) {
  40268. if (subdivisions === void 0) { subdivisions = 1; }
  40269. if (mesh === void 0) { mesh = null; }
  40270. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40271. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40272. _this.height = height;
  40273. _this.diameterTop = diameterTop;
  40274. _this.diameterBottom = diameterBottom;
  40275. _this.tessellation = tessellation;
  40276. _this.subdivisions = subdivisions;
  40277. _this.side = side;
  40278. return _this;
  40279. }
  40280. /** @hidden */
  40281. CylinderGeometry.prototype._regenerateVertexData = function () {
  40282. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40283. };
  40284. CylinderGeometry.prototype.copy = function (id) {
  40285. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40286. };
  40287. CylinderGeometry.prototype.serialize = function () {
  40288. var serializationObject = _super.prototype.serialize.call(this);
  40289. serializationObject.height = this.height;
  40290. serializationObject.diameterTop = this.diameterTop;
  40291. serializationObject.diameterBottom = this.diameterBottom;
  40292. serializationObject.tessellation = this.tessellation;
  40293. return serializationObject;
  40294. };
  40295. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40296. if (scene.getGeometryByID(parsedCylinder.id)) {
  40297. return null; // null since geometry could be something else than a cylinder...
  40298. }
  40299. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40300. if (BABYLON.Tags) {
  40301. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40302. }
  40303. scene.pushGeometry(cylinder, true);
  40304. return cylinder;
  40305. };
  40306. return CylinderGeometry;
  40307. }(_PrimitiveGeometry));
  40308. BABYLON.CylinderGeometry = CylinderGeometry;
  40309. /**
  40310. * Creates a new torus geometry
  40311. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40312. */
  40313. var TorusGeometry = /** @class */ (function (_super) {
  40314. __extends(TorusGeometry, _super);
  40315. /**
  40316. * Creates a new torus geometry
  40317. * @param id defines the unique ID of the geometry
  40318. * @param scene defines the hosting scene
  40319. * @param diameter defines the diameter of the torus
  40320. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40321. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40322. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40323. * @param mesh defines the hosting mesh (can be null)
  40324. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40325. */
  40326. function TorusGeometry(id, scene,
  40327. /**
  40328. * Defines the diameter of the torus
  40329. */
  40330. diameter,
  40331. /**
  40332. * Defines the thickness of the torus (ie. internal diameter)
  40333. */
  40334. thickness,
  40335. /**
  40336. * Defines the tesselation factor to apply to the torus
  40337. */
  40338. tessellation, canBeRegenerated, mesh,
  40339. /**
  40340. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40341. */
  40342. side) {
  40343. if (mesh === void 0) { mesh = null; }
  40344. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40345. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40346. _this.diameter = diameter;
  40347. _this.thickness = thickness;
  40348. _this.tessellation = tessellation;
  40349. _this.side = side;
  40350. return _this;
  40351. }
  40352. /** @hidden */
  40353. TorusGeometry.prototype._regenerateVertexData = function () {
  40354. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40355. };
  40356. TorusGeometry.prototype.copy = function (id) {
  40357. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40358. };
  40359. TorusGeometry.prototype.serialize = function () {
  40360. var serializationObject = _super.prototype.serialize.call(this);
  40361. serializationObject.diameter = this.diameter;
  40362. serializationObject.thickness = this.thickness;
  40363. serializationObject.tessellation = this.tessellation;
  40364. return serializationObject;
  40365. };
  40366. TorusGeometry.Parse = function (parsedTorus, scene) {
  40367. if (scene.getGeometryByID(parsedTorus.id)) {
  40368. return null; // null since geometry could be something else than a torus...
  40369. }
  40370. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40371. if (BABYLON.Tags) {
  40372. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40373. }
  40374. scene.pushGeometry(torus, true);
  40375. return torus;
  40376. };
  40377. return TorusGeometry;
  40378. }(_PrimitiveGeometry));
  40379. BABYLON.TorusGeometry = TorusGeometry;
  40380. /**
  40381. * Creates a new ground geometry
  40382. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40383. */
  40384. var GroundGeometry = /** @class */ (function (_super) {
  40385. __extends(GroundGeometry, _super);
  40386. /**
  40387. * Creates a new ground geometry
  40388. * @param id defines the unique ID of the geometry
  40389. * @param scene defines the hosting scene
  40390. * @param width defines the width of the ground
  40391. * @param height defines the height of the ground
  40392. * @param subdivisions defines the subdivisions to apply to the ground
  40393. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40394. * @param mesh defines the hosting mesh (can be null)
  40395. */
  40396. function GroundGeometry(id, scene,
  40397. /**
  40398. * Defines the width of the ground
  40399. */
  40400. width,
  40401. /**
  40402. * Defines the height of the ground
  40403. */
  40404. height,
  40405. /**
  40406. * Defines the subdivisions to apply to the ground
  40407. */
  40408. subdivisions, canBeRegenerated, mesh) {
  40409. if (mesh === void 0) { mesh = null; }
  40410. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40411. _this.width = width;
  40412. _this.height = height;
  40413. _this.subdivisions = subdivisions;
  40414. return _this;
  40415. }
  40416. /** @hidden */
  40417. GroundGeometry.prototype._regenerateVertexData = function () {
  40418. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40419. };
  40420. GroundGeometry.prototype.copy = function (id) {
  40421. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40422. };
  40423. GroundGeometry.prototype.serialize = function () {
  40424. var serializationObject = _super.prototype.serialize.call(this);
  40425. serializationObject.width = this.width;
  40426. serializationObject.height = this.height;
  40427. serializationObject.subdivisions = this.subdivisions;
  40428. return serializationObject;
  40429. };
  40430. GroundGeometry.Parse = function (parsedGround, scene) {
  40431. if (scene.getGeometryByID(parsedGround.id)) {
  40432. return null; // null since geometry could be something else than a ground...
  40433. }
  40434. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40435. if (BABYLON.Tags) {
  40436. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40437. }
  40438. scene.pushGeometry(ground, true);
  40439. return ground;
  40440. };
  40441. return GroundGeometry;
  40442. }(_PrimitiveGeometry));
  40443. BABYLON.GroundGeometry = GroundGeometry;
  40444. /**
  40445. * Creates a tiled ground geometry
  40446. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40447. */
  40448. var TiledGroundGeometry = /** @class */ (function (_super) {
  40449. __extends(TiledGroundGeometry, _super);
  40450. /**
  40451. * Creates a tiled ground geometry
  40452. * @param id defines the unique ID of the geometry
  40453. * @param scene defines the hosting scene
  40454. * @param xmin defines the minimum value on X axis
  40455. * @param zmin defines the minimum value on Z axis
  40456. * @param xmax defines the maximum value on X axis
  40457. * @param zmax defines the maximum value on Z axis
  40458. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40459. * @param precision defines the precision to use when computing the tiles
  40460. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40461. * @param mesh defines the hosting mesh (can be null)
  40462. */
  40463. function TiledGroundGeometry(id, scene,
  40464. /**
  40465. * Defines the minimum value on X axis
  40466. */
  40467. xmin,
  40468. /**
  40469. * Defines the minimum value on Z axis
  40470. */
  40471. zmin,
  40472. /**
  40473. * Defines the maximum value on X axis
  40474. */
  40475. xmax,
  40476. /**
  40477. * Defines the maximum value on Z axis
  40478. */
  40479. zmax,
  40480. /**
  40481. * Defines the subdivisions to apply to the ground
  40482. */
  40483. subdivisions,
  40484. /**
  40485. * Defines the precision to use when computing the tiles
  40486. */
  40487. precision, canBeRegenerated, mesh) {
  40488. if (mesh === void 0) { mesh = null; }
  40489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40490. _this.xmin = xmin;
  40491. _this.zmin = zmin;
  40492. _this.xmax = xmax;
  40493. _this.zmax = zmax;
  40494. _this.subdivisions = subdivisions;
  40495. _this.precision = precision;
  40496. return _this;
  40497. }
  40498. /** @hidden */
  40499. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40500. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40501. };
  40502. TiledGroundGeometry.prototype.copy = function (id) {
  40503. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40504. };
  40505. return TiledGroundGeometry;
  40506. }(_PrimitiveGeometry));
  40507. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40508. /**
  40509. * Creates a plane geometry
  40510. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40511. */
  40512. var PlaneGeometry = /** @class */ (function (_super) {
  40513. __extends(PlaneGeometry, _super);
  40514. /**
  40515. * Creates a plane geometry
  40516. * @param id defines the unique ID of the geometry
  40517. * @param scene defines the hosting scene
  40518. * @param size defines the size of the plane (width === height)
  40519. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40520. * @param mesh defines the hosting mesh (can be null)
  40521. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40522. */
  40523. function PlaneGeometry(id, scene,
  40524. /**
  40525. * Defines the size of the plane (width === height)
  40526. */
  40527. size, canBeRegenerated, mesh,
  40528. /**
  40529. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40530. */
  40531. side) {
  40532. if (mesh === void 0) { mesh = null; }
  40533. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40534. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40535. _this.size = size;
  40536. _this.side = side;
  40537. return _this;
  40538. }
  40539. /** @hidden */
  40540. PlaneGeometry.prototype._regenerateVertexData = function () {
  40541. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40542. };
  40543. PlaneGeometry.prototype.copy = function (id) {
  40544. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40545. };
  40546. PlaneGeometry.prototype.serialize = function () {
  40547. var serializationObject = _super.prototype.serialize.call(this);
  40548. serializationObject.size = this.size;
  40549. return serializationObject;
  40550. };
  40551. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40552. if (scene.getGeometryByID(parsedPlane.id)) {
  40553. return null; // null since geometry could be something else than a ground...
  40554. }
  40555. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40556. if (BABYLON.Tags) {
  40557. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40558. }
  40559. scene.pushGeometry(plane, true);
  40560. return plane;
  40561. };
  40562. return PlaneGeometry;
  40563. }(_PrimitiveGeometry));
  40564. BABYLON.PlaneGeometry = PlaneGeometry;
  40565. /**
  40566. * Creates a torus knot geometry
  40567. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40568. */
  40569. var TorusKnotGeometry = /** @class */ (function (_super) {
  40570. __extends(TorusKnotGeometry, _super);
  40571. /**
  40572. * Creates a torus knot geometry
  40573. * @param id defines the unique ID of the geometry
  40574. * @param scene defines the hosting scene
  40575. * @param radius defines the radius of the torus knot
  40576. * @param tube defines the thickness of the torus knot tube
  40577. * @param radialSegments defines the number of radial segments
  40578. * @param tubularSegments defines the number of tubular segments
  40579. * @param p defines the first number of windings
  40580. * @param q defines the second number of windings
  40581. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40582. * @param mesh defines the hosting mesh (can be null)
  40583. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40584. */
  40585. function TorusKnotGeometry(id, scene,
  40586. /**
  40587. * Defines the radius of the torus knot
  40588. */
  40589. radius,
  40590. /**
  40591. * Defines the thickness of the torus knot tube
  40592. */
  40593. tube,
  40594. /**
  40595. * Defines the number of radial segments
  40596. */
  40597. radialSegments,
  40598. /**
  40599. * Defines the number of tubular segments
  40600. */
  40601. tubularSegments,
  40602. /**
  40603. * Defines the first number of windings
  40604. */
  40605. p,
  40606. /**
  40607. * Defines the second number of windings
  40608. */
  40609. q, canBeRegenerated, mesh,
  40610. /**
  40611. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40612. */
  40613. side) {
  40614. if (mesh === void 0) { mesh = null; }
  40615. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40616. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40617. _this.radius = radius;
  40618. _this.tube = tube;
  40619. _this.radialSegments = radialSegments;
  40620. _this.tubularSegments = tubularSegments;
  40621. _this.p = p;
  40622. _this.q = q;
  40623. _this.side = side;
  40624. return _this;
  40625. }
  40626. /** @hidden */
  40627. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40628. 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 });
  40629. };
  40630. TorusKnotGeometry.prototype.copy = function (id) {
  40631. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40632. };
  40633. TorusKnotGeometry.prototype.serialize = function () {
  40634. var serializationObject = _super.prototype.serialize.call(this);
  40635. serializationObject.radius = this.radius;
  40636. serializationObject.tube = this.tube;
  40637. serializationObject.radialSegments = this.radialSegments;
  40638. serializationObject.tubularSegments = this.tubularSegments;
  40639. serializationObject.p = this.p;
  40640. serializationObject.q = this.q;
  40641. return serializationObject;
  40642. };
  40643. ;
  40644. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40645. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40646. return null; // null since geometry could be something else than a ground...
  40647. }
  40648. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40649. if (BABYLON.Tags) {
  40650. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40651. }
  40652. scene.pushGeometry(torusKnot, true);
  40653. return torusKnot;
  40654. };
  40655. return TorusKnotGeometry;
  40656. }(_PrimitiveGeometry));
  40657. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40658. //}
  40659. })(BABYLON || (BABYLON = {}));
  40660. //# sourceMappingURL=babylon.geometry.js.map
  40661. var BABYLON;
  40662. (function (BABYLON) {
  40663. /**
  40664. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40665. */
  40666. var PerformanceMonitor = /** @class */ (function () {
  40667. /**
  40668. * constructor
  40669. * @param frameSampleSize The number of samples required to saturate the sliding window
  40670. */
  40671. function PerformanceMonitor(frameSampleSize) {
  40672. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40673. this._enabled = true;
  40674. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40675. }
  40676. /**
  40677. * Samples current frame
  40678. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40679. */
  40680. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40681. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40682. if (!this._enabled)
  40683. return;
  40684. if (this._lastFrameTimeMs != null) {
  40685. var dt = timeMs - this._lastFrameTimeMs;
  40686. this._rollingFrameTime.add(dt);
  40687. }
  40688. this._lastFrameTimeMs = timeMs;
  40689. };
  40690. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40691. /**
  40692. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40693. * @return Average frame time in milliseconds
  40694. */
  40695. get: function () {
  40696. return this._rollingFrameTime.average;
  40697. },
  40698. enumerable: true,
  40699. configurable: true
  40700. });
  40701. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40702. /**
  40703. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40704. * @return Frame time variance in milliseconds squared
  40705. */
  40706. get: function () {
  40707. return this._rollingFrameTime.variance;
  40708. },
  40709. enumerable: true,
  40710. configurable: true
  40711. });
  40712. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40713. /**
  40714. * Returns the frame time of the most recent frame
  40715. * @return Frame time in milliseconds
  40716. */
  40717. get: function () {
  40718. return this._rollingFrameTime.history(0);
  40719. },
  40720. enumerable: true,
  40721. configurable: true
  40722. });
  40723. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40724. /**
  40725. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40726. * @return Framerate in frames per second
  40727. */
  40728. get: function () {
  40729. return 1000.0 / this._rollingFrameTime.average;
  40730. },
  40731. enumerable: true,
  40732. configurable: true
  40733. });
  40734. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40735. /**
  40736. * Returns the average framerate in frames per second using the most recent frame time
  40737. * @return Framerate in frames per second
  40738. */
  40739. get: function () {
  40740. var history = this._rollingFrameTime.history(0);
  40741. if (history === 0) {
  40742. return 0;
  40743. }
  40744. return 1000.0 / history;
  40745. },
  40746. enumerable: true,
  40747. configurable: true
  40748. });
  40749. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40750. /**
  40751. * Returns true if enough samples have been taken to completely fill the sliding window
  40752. * @return true if saturated
  40753. */
  40754. get: function () {
  40755. return this._rollingFrameTime.isSaturated();
  40756. },
  40757. enumerable: true,
  40758. configurable: true
  40759. });
  40760. /**
  40761. * Enables contributions to the sliding window sample set
  40762. */
  40763. PerformanceMonitor.prototype.enable = function () {
  40764. this._enabled = true;
  40765. };
  40766. /**
  40767. * Disables contributions to the sliding window sample set
  40768. * Samples will not be interpolated over the disabled period
  40769. */
  40770. PerformanceMonitor.prototype.disable = function () {
  40771. this._enabled = false;
  40772. //clear last sample to avoid interpolating over the disabled period when next enabled
  40773. this._lastFrameTimeMs = null;
  40774. };
  40775. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40776. /**
  40777. * Returns true if sampling is enabled
  40778. * @return true if enabled
  40779. */
  40780. get: function () {
  40781. return this._enabled;
  40782. },
  40783. enumerable: true,
  40784. configurable: true
  40785. });
  40786. /**
  40787. * Resets performance monitor
  40788. */
  40789. PerformanceMonitor.prototype.reset = function () {
  40790. //clear last sample to avoid interpolating over the disabled period when next enabled
  40791. this._lastFrameTimeMs = null;
  40792. //wipe record
  40793. this._rollingFrameTime.reset();
  40794. };
  40795. return PerformanceMonitor;
  40796. }());
  40797. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40798. /**
  40799. * RollingAverage
  40800. *
  40801. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40802. */
  40803. var RollingAverage = /** @class */ (function () {
  40804. /**
  40805. * constructor
  40806. * @param length The number of samples required to saturate the sliding window
  40807. */
  40808. function RollingAverage(length) {
  40809. this._samples = new Array(length);
  40810. this.reset();
  40811. }
  40812. /**
  40813. * Adds a sample to the sample set
  40814. * @param v The sample value
  40815. */
  40816. RollingAverage.prototype.add = function (v) {
  40817. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40818. var delta;
  40819. //we need to check if we've already wrapped round
  40820. if (this.isSaturated()) {
  40821. //remove bottom of stack from mean
  40822. var bottomValue = this._samples[this._pos];
  40823. delta = bottomValue - this.average;
  40824. this.average -= delta / (this._sampleCount - 1);
  40825. this._m2 -= delta * (bottomValue - this.average);
  40826. }
  40827. else {
  40828. this._sampleCount++;
  40829. }
  40830. //add new value to mean
  40831. delta = v - this.average;
  40832. this.average += delta / (this._sampleCount);
  40833. this._m2 += delta * (v - this.average);
  40834. //set the new variance
  40835. this.variance = this._m2 / (this._sampleCount - 1);
  40836. this._samples[this._pos] = v;
  40837. this._pos++;
  40838. this._pos %= this._samples.length; //positive wrap around
  40839. };
  40840. /**
  40841. * Returns previously added values or null if outside of history or outside the sliding window domain
  40842. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40843. * @return Value previously recorded with add() or null if outside of range
  40844. */
  40845. RollingAverage.prototype.history = function (i) {
  40846. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40847. return 0;
  40848. }
  40849. var i0 = this._wrapPosition(this._pos - 1.0);
  40850. return this._samples[this._wrapPosition(i0 - i)];
  40851. };
  40852. /**
  40853. * Returns true if enough samples have been taken to completely fill the sliding window
  40854. * @return true if sample-set saturated
  40855. */
  40856. RollingAverage.prototype.isSaturated = function () {
  40857. return this._sampleCount >= this._samples.length;
  40858. };
  40859. /**
  40860. * Resets the rolling average (equivalent to 0 samples taken so far)
  40861. */
  40862. RollingAverage.prototype.reset = function () {
  40863. this.average = 0;
  40864. this.variance = 0;
  40865. this._sampleCount = 0;
  40866. this._pos = 0;
  40867. this._m2 = 0;
  40868. };
  40869. /**
  40870. * Wraps a value around the sample range boundaries
  40871. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40872. * @return Wrapped position in sample range
  40873. */
  40874. RollingAverage.prototype._wrapPosition = function (i) {
  40875. var max = this._samples.length;
  40876. return ((i % max) + max) % max;
  40877. };
  40878. return RollingAverage;
  40879. }());
  40880. BABYLON.RollingAverage = RollingAverage;
  40881. })(BABYLON || (BABYLON = {}));
  40882. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40883. var BABYLON;
  40884. (function (BABYLON) {
  40885. /**
  40886. * "Static Class" containing the most commonly used helper while dealing with material for
  40887. * rendering purpose.
  40888. *
  40889. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40890. *
  40891. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40892. */
  40893. var MaterialHelper = /** @class */ (function () {
  40894. function MaterialHelper() {
  40895. }
  40896. /**
  40897. * Bind the current view position to an effect.
  40898. * @param effect The effect to be bound
  40899. * @param scene The scene the eyes position is used from
  40900. */
  40901. MaterialHelper.BindEyePosition = function (effect, scene) {
  40902. if (scene._forcedViewPosition) {
  40903. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40904. return;
  40905. }
  40906. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40907. };
  40908. /**
  40909. * Helps preparing the defines values about the UVs in used in the effect.
  40910. * UVs are shared as much as we can accross chanels in the shaders.
  40911. * @param texture The texture we are preparing the UVs for
  40912. * @param defines The defines to update
  40913. * @param key The chanel key "diffuse", "specular"... used in the shader
  40914. */
  40915. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40916. defines._needUVs = true;
  40917. defines[key] = true;
  40918. if (texture.getTextureMatrix().isIdentity(true)) {
  40919. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40920. if (texture.coordinatesIndex === 0) {
  40921. defines["MAINUV1"] = true;
  40922. }
  40923. else {
  40924. defines["MAINUV2"] = true;
  40925. }
  40926. }
  40927. else {
  40928. defines[key + "DIRECTUV"] = 0;
  40929. }
  40930. };
  40931. /**
  40932. * Binds a texture matrix value to its corrsponding uniform
  40933. * @param texture The texture to bind the matrix for
  40934. * @param uniformBuffer The uniform buffer receivin the data
  40935. * @param key The chanel key "diffuse", "specular"... used in the shader
  40936. */
  40937. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40938. var matrix = texture.getTextureMatrix();
  40939. if (!matrix.isIdentity(true)) {
  40940. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40941. }
  40942. };
  40943. /**
  40944. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40945. * @param mesh defines the current mesh
  40946. * @param scene defines the current scene
  40947. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40948. * @param pointsCloud defines if point cloud rendering has to be turned on
  40949. * @param fogEnabled defines if fog has to be turned on
  40950. * @param alphaTest defines if alpha testing has to be turned on
  40951. * @param defines defines the current list of defines
  40952. */
  40953. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40954. if (defines._areMiscDirty) {
  40955. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40956. defines["POINTSIZE"] = pointsCloud;
  40957. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40958. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40959. defines["ALPHATEST"] = alphaTest;
  40960. }
  40961. };
  40962. /**
  40963. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40964. * @param scene defines the current scene
  40965. * @param engine defines the current engine
  40966. * @param defines specifies the list of active defines
  40967. * @param useInstances defines if instances have to be turned on
  40968. * @param useClipPlane defines if clip plane have to be turned on
  40969. */
  40970. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40971. if (useClipPlane === void 0) { useClipPlane = null; }
  40972. var changed = false;
  40973. var useClipPlane1 = false;
  40974. var useClipPlane2 = false;
  40975. var useClipPlane3 = false;
  40976. var useClipPlane4 = false;
  40977. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40978. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40979. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40980. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40981. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40982. defines["CLIPPLANE"] = useClipPlane1;
  40983. changed = true;
  40984. }
  40985. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40986. defines["CLIPPLANE2"] = useClipPlane2;
  40987. changed = true;
  40988. }
  40989. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40990. defines["CLIPPLANE3"] = useClipPlane3;
  40991. changed = true;
  40992. }
  40993. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40994. defines["CLIPPLANE4"] = useClipPlane4;
  40995. changed = true;
  40996. }
  40997. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40998. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40999. changed = true;
  41000. }
  41001. if (defines["INSTANCES"] !== useInstances) {
  41002. defines["INSTANCES"] = useInstances;
  41003. changed = true;
  41004. }
  41005. if (changed) {
  41006. defines.markAsUnprocessed();
  41007. }
  41008. };
  41009. /**
  41010. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41011. * @param mesh The mesh containing the geometry data we will draw
  41012. * @param defines The defines to update
  41013. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41014. * @param useBones Precise whether bones should be used or not (override mesh info)
  41015. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41016. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41017. * @returns false if defines are considered not dirty and have not been checked
  41018. */
  41019. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41020. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41021. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41022. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41023. return false;
  41024. }
  41025. defines._normals = defines._needNormals;
  41026. defines._uvs = defines._needUVs;
  41027. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41028. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41029. defines["TANGENT"] = true;
  41030. }
  41031. if (defines._needUVs) {
  41032. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41033. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41034. }
  41035. else {
  41036. defines["UV1"] = false;
  41037. defines["UV2"] = false;
  41038. }
  41039. if (useVertexColor) {
  41040. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41041. defines["VERTEXCOLOR"] = hasVertexColors;
  41042. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41043. }
  41044. if (useBones) {
  41045. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41046. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41047. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41048. }
  41049. else {
  41050. defines["NUM_BONE_INFLUENCERS"] = 0;
  41051. defines["BonesPerMesh"] = 0;
  41052. }
  41053. }
  41054. if (useMorphTargets) {
  41055. var manager = mesh.morphTargetManager;
  41056. if (manager) {
  41057. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41058. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41059. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41060. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41061. }
  41062. else {
  41063. defines["MORPHTARGETS_TANGENT"] = false;
  41064. defines["MORPHTARGETS_NORMAL"] = false;
  41065. defines["MORPHTARGETS"] = false;
  41066. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41067. }
  41068. }
  41069. return true;
  41070. };
  41071. /**
  41072. * Prepares the defines related to the light information passed in parameter
  41073. * @param scene The scene we are intending to draw
  41074. * @param mesh The mesh the effect is compiling for
  41075. * @param defines The defines to update
  41076. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41077. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41078. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41079. * @returns true if normals will be required for the rest of the effect
  41080. */
  41081. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41082. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41083. if (disableLighting === void 0) { disableLighting = false; }
  41084. if (!defines._areLightsDirty) {
  41085. return defines._needNormals;
  41086. }
  41087. var lightIndex = 0;
  41088. var needNormals = false;
  41089. var needRebuild = false;
  41090. var lightmapMode = false;
  41091. var shadowEnabled = false;
  41092. var specularEnabled = false;
  41093. if (scene.lightsEnabled && !disableLighting) {
  41094. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41095. var light = _a[_i];
  41096. needNormals = true;
  41097. if (defines["LIGHT" + lightIndex] === undefined) {
  41098. needRebuild = true;
  41099. }
  41100. defines["LIGHT" + lightIndex] = true;
  41101. defines["SPOTLIGHT" + lightIndex] = false;
  41102. defines["HEMILIGHT" + lightIndex] = false;
  41103. defines["POINTLIGHT" + lightIndex] = false;
  41104. defines["DIRLIGHT" + lightIndex] = false;
  41105. light.prepareLightSpecificDefines(defines, lightIndex);
  41106. // FallOff.
  41107. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41108. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41109. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41110. switch (light.falloffType) {
  41111. case BABYLON.Light.FALLOFF_GLTF:
  41112. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41113. break;
  41114. case BABYLON.Light.FALLOFF_PHYSICAL:
  41115. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41116. break;
  41117. case BABYLON.Light.FALLOFF_STANDARD:
  41118. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41119. break;
  41120. }
  41121. // Specular
  41122. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41123. specularEnabled = true;
  41124. }
  41125. // Shadows
  41126. defines["SHADOW" + lightIndex] = false;
  41127. defines["SHADOWPCF" + lightIndex] = false;
  41128. defines["SHADOWPCSS" + lightIndex] = false;
  41129. defines["SHADOWPOISSON" + lightIndex] = false;
  41130. defines["SHADOWESM" + lightIndex] = false;
  41131. defines["SHADOWCUBE" + lightIndex] = false;
  41132. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41133. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41134. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41135. var shadowGenerator = light.getShadowGenerator();
  41136. if (shadowGenerator) {
  41137. var shadowMap = shadowGenerator.getShadowMap();
  41138. if (shadowMap) {
  41139. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41140. shadowEnabled = true;
  41141. shadowGenerator.prepareDefines(defines, lightIndex);
  41142. }
  41143. }
  41144. }
  41145. }
  41146. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41147. lightmapMode = true;
  41148. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41149. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41150. }
  41151. else {
  41152. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41153. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41154. }
  41155. lightIndex++;
  41156. if (lightIndex === maxSimultaneousLights)
  41157. break;
  41158. }
  41159. }
  41160. defines["SPECULARTERM"] = specularEnabled;
  41161. defines["SHADOWS"] = shadowEnabled;
  41162. // Resetting all other lights if any
  41163. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41164. if (defines["LIGHT" + index] !== undefined) {
  41165. defines["LIGHT" + index] = false;
  41166. defines["HEMILIGHT" + lightIndex] = false;
  41167. defines["POINTLIGHT" + lightIndex] = false;
  41168. defines["DIRLIGHT" + lightIndex] = false;
  41169. defines["SPOTLIGHT" + lightIndex] = false;
  41170. defines["SHADOW" + lightIndex] = false;
  41171. }
  41172. }
  41173. var caps = scene.getEngine().getCaps();
  41174. if (defines["SHADOWFLOAT"] === undefined) {
  41175. needRebuild = true;
  41176. }
  41177. defines["SHADOWFLOAT"] = shadowEnabled &&
  41178. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41179. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41180. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41181. if (needRebuild) {
  41182. defines.rebuild();
  41183. }
  41184. return needNormals;
  41185. };
  41186. /**
  41187. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41188. * that won t be acctive due to defines being turned off.
  41189. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41190. * @param samplersList The samplers list
  41191. * @param defines The defines helping in the list generation
  41192. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41193. */
  41194. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41195. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41196. var uniformsList;
  41197. var uniformBuffersList = null;
  41198. if (uniformsListOrOptions.uniformsNames) {
  41199. var options = uniformsListOrOptions;
  41200. uniformsList = options.uniformsNames;
  41201. uniformBuffersList = options.uniformBuffersNames;
  41202. samplersList = options.samplers;
  41203. defines = options.defines;
  41204. maxSimultaneousLights = options.maxSimultaneousLights;
  41205. }
  41206. else {
  41207. uniformsList = uniformsListOrOptions;
  41208. if (!samplersList) {
  41209. samplersList = [];
  41210. }
  41211. }
  41212. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41213. if (!defines["LIGHT" + lightIndex]) {
  41214. break;
  41215. }
  41216. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41217. if (uniformBuffersList) {
  41218. uniformBuffersList.push("Light" + lightIndex);
  41219. }
  41220. samplersList.push("shadowSampler" + lightIndex);
  41221. samplersList.push("depthSampler" + lightIndex);
  41222. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41223. samplersList.push("projectionLightSampler" + lightIndex);
  41224. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41225. }
  41226. }
  41227. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41228. uniformsList.push("morphTargetInfluences");
  41229. }
  41230. };
  41231. /**
  41232. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41233. * @param defines The defines to update while falling back
  41234. * @param fallbacks The authorized effect fallbacks
  41235. * @param maxSimultaneousLights The maximum number of lights allowed
  41236. * @param rank the current rank of the Effect
  41237. * @returns The newly affected rank
  41238. */
  41239. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41240. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41241. if (rank === void 0) { rank = 0; }
  41242. var lightFallbackRank = 0;
  41243. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41244. if (!defines["LIGHT" + lightIndex]) {
  41245. break;
  41246. }
  41247. if (lightIndex > 0) {
  41248. lightFallbackRank = rank + lightIndex;
  41249. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41250. }
  41251. if (!defines["SHADOWS"]) {
  41252. if (defines["SHADOW" + lightIndex]) {
  41253. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41254. }
  41255. if (defines["SHADOWPCF" + lightIndex]) {
  41256. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41257. }
  41258. if (defines["SHADOWPCSS" + lightIndex]) {
  41259. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41260. }
  41261. if (defines["SHADOWPOISSON" + lightIndex]) {
  41262. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41263. }
  41264. if (defines["SHADOWESM" + lightIndex]) {
  41265. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41266. }
  41267. }
  41268. }
  41269. return lightFallbackRank++;
  41270. };
  41271. /**
  41272. * Prepares the list of attributes required for morph targets according to the effect defines.
  41273. * @param attribs The current list of supported attribs
  41274. * @param mesh The mesh to prepare the morph targets attributes for
  41275. * @param defines The current Defines of the effect
  41276. */
  41277. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41278. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41279. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41280. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41281. var manager = mesh.morphTargetManager;
  41282. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41283. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41284. for (var index = 0; index < influencers; index++) {
  41285. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41286. if (normal) {
  41287. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41288. }
  41289. if (tangent) {
  41290. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41291. }
  41292. if (attribs.length > maxAttributesCount) {
  41293. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41294. }
  41295. }
  41296. }
  41297. };
  41298. /**
  41299. * Prepares the list of attributes required for bones according to the effect defines.
  41300. * @param attribs The current list of supported attribs
  41301. * @param mesh The mesh to prepare the bones attributes for
  41302. * @param defines The current Defines of the effect
  41303. * @param fallbacks The current efffect fallback strategy
  41304. */
  41305. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41306. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41307. fallbacks.addCPUSkinningFallback(0, mesh);
  41308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41310. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41313. }
  41314. }
  41315. };
  41316. /**
  41317. * Prepares the list of attributes required for instances according to the effect defines.
  41318. * @param attribs The current list of supported attribs
  41319. * @param defines The current Defines of the effect
  41320. */
  41321. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41322. if (defines["INSTANCES"]) {
  41323. attribs.push("world0");
  41324. attribs.push("world1");
  41325. attribs.push("world2");
  41326. attribs.push("world3");
  41327. }
  41328. };
  41329. /**
  41330. * Binds the light shadow information to the effect for the given mesh.
  41331. * @param light The light containing the generator
  41332. * @param scene The scene the lights belongs to
  41333. * @param mesh The mesh we are binding the information to render
  41334. * @param lightIndex The light index in the effect used to render the mesh
  41335. * @param effect The effect we are binding the data to
  41336. */
  41337. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41338. if (light.shadowEnabled && mesh.receiveShadows) {
  41339. var shadowGenerator = light.getShadowGenerator();
  41340. if (shadowGenerator) {
  41341. shadowGenerator.bindShadowLight(lightIndex, effect);
  41342. }
  41343. }
  41344. };
  41345. /**
  41346. * Binds the light information to the effect.
  41347. * @param light The light containing the generator
  41348. * @param effect The effect we are binding the data to
  41349. * @param lightIndex The light index in the effect used to render
  41350. */
  41351. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41352. light.transferToEffect(effect, lightIndex + "");
  41353. };
  41354. /**
  41355. * Binds the lights information from the scene to the effect for the given mesh.
  41356. * @param scene The scene the lights belongs to
  41357. * @param mesh The mesh we are binding the information to render
  41358. * @param effect The effect we are binding the data to
  41359. * @param defines The generated defines for the effect
  41360. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41361. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41362. */
  41363. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41364. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41365. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41366. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41367. for (var i = 0; i < len; i++) {
  41368. var light = mesh._lightSources[i];
  41369. var iAsString = i.toString();
  41370. var scaledIntensity = light.getScaledIntensity();
  41371. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41372. MaterialHelper.BindLightProperties(light, effect, i);
  41373. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41374. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41375. if (defines["SPECULARTERM"]) {
  41376. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41377. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41378. }
  41379. // Shadows
  41380. if (scene.shadowsEnabled) {
  41381. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41382. }
  41383. light._uniformBuffer.update();
  41384. }
  41385. };
  41386. /**
  41387. * Binds the fog information from the scene to the effect for the given mesh.
  41388. * @param scene The scene the lights belongs to
  41389. * @param mesh The mesh we are binding the information to render
  41390. * @param effect The effect we are binding the data to
  41391. */
  41392. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41393. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41394. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41395. effect.setColor3("vFogColor", scene.fogColor);
  41396. }
  41397. };
  41398. /**
  41399. * Binds the bones information from the mesh to the effect.
  41400. * @param mesh The mesh we are binding the information to render
  41401. * @param effect The effect we are binding the data to
  41402. */
  41403. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41404. if (!effect || !mesh) {
  41405. return;
  41406. }
  41407. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41408. mesh.computeBonesUsingShaders = false;
  41409. }
  41410. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41411. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41412. if (matrices) {
  41413. effect.setMatrices("mBones", matrices);
  41414. }
  41415. }
  41416. };
  41417. /**
  41418. * Binds the morph targets information from the mesh to the effect.
  41419. * @param abstractMesh The mesh we are binding the information to render
  41420. * @param effect The effect we are binding the data to
  41421. */
  41422. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41423. var manager = abstractMesh.morphTargetManager;
  41424. if (!abstractMesh || !manager) {
  41425. return;
  41426. }
  41427. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41428. };
  41429. /**
  41430. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41431. * @param defines The generated defines used in the effect
  41432. * @param effect The effect we are binding the data to
  41433. * @param scene The scene we are willing to render with logarithmic scale for
  41434. */
  41435. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41436. if (defines["LOGARITHMICDEPTH"]) {
  41437. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41438. }
  41439. };
  41440. /**
  41441. * Binds the clip plane information from the scene to the effect.
  41442. * @param scene The scene the clip plane information are extracted from
  41443. * @param effect The effect we are binding the data to
  41444. */
  41445. MaterialHelper.BindClipPlane = function (effect, scene) {
  41446. if (scene.clipPlane) {
  41447. var clipPlane = scene.clipPlane;
  41448. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41449. }
  41450. if (scene.clipPlane2) {
  41451. var clipPlane = scene.clipPlane2;
  41452. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41453. }
  41454. if (scene.clipPlane3) {
  41455. var clipPlane = scene.clipPlane3;
  41456. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41457. }
  41458. if (scene.clipPlane4) {
  41459. var clipPlane = scene.clipPlane4;
  41460. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41461. }
  41462. };
  41463. return MaterialHelper;
  41464. }());
  41465. BABYLON.MaterialHelper = MaterialHelper;
  41466. })(BABYLON || (BABYLON = {}));
  41467. //# sourceMappingURL=babylon.materialHelper.js.map
  41468. var BABYLON;
  41469. (function (BABYLON) {
  41470. var PushMaterial = /** @class */ (function (_super) {
  41471. __extends(PushMaterial, _super);
  41472. function PushMaterial(name, scene) {
  41473. var _this = _super.call(this, name, scene) || this;
  41474. _this._normalMatrix = new BABYLON.Matrix();
  41475. _this.storeEffectOnSubMeshes = true;
  41476. return _this;
  41477. }
  41478. PushMaterial.prototype.getEffect = function () {
  41479. return this._activeEffect;
  41480. };
  41481. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41482. if (!mesh) {
  41483. return false;
  41484. }
  41485. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41486. return true;
  41487. }
  41488. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41489. };
  41490. /**
  41491. * Binds the given world matrix to the active effect
  41492. *
  41493. * @param world the matrix to bind
  41494. */
  41495. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41496. this._activeEffect.setMatrix("world", world);
  41497. };
  41498. /**
  41499. * Binds the given normal matrix to the active effect
  41500. *
  41501. * @param normalMatrix the matrix to bind
  41502. */
  41503. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41504. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41505. };
  41506. PushMaterial.prototype.bind = function (world, mesh) {
  41507. if (!mesh) {
  41508. return;
  41509. }
  41510. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41511. };
  41512. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41513. if (effect === void 0) { effect = null; }
  41514. _super.prototype._afterBind.call(this, mesh);
  41515. this.getScene()._cachedEffect = effect;
  41516. };
  41517. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41518. if (visibility === void 0) { visibility = 1; }
  41519. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41520. };
  41521. return PushMaterial;
  41522. }(BABYLON.Material));
  41523. BABYLON.PushMaterial = PushMaterial;
  41524. })(BABYLON || (BABYLON = {}));
  41525. //# sourceMappingURL=babylon.pushMaterial.js.map
  41526. var BABYLON;
  41527. (function (BABYLON) {
  41528. /** @hidden */
  41529. var StandardMaterialDefines = /** @class */ (function (_super) {
  41530. __extends(StandardMaterialDefines, _super);
  41531. function StandardMaterialDefines() {
  41532. var _this = _super.call(this) || this;
  41533. _this.MAINUV1 = false;
  41534. _this.MAINUV2 = false;
  41535. _this.DIFFUSE = false;
  41536. _this.DIFFUSEDIRECTUV = 0;
  41537. _this.AMBIENT = false;
  41538. _this.AMBIENTDIRECTUV = 0;
  41539. _this.OPACITY = false;
  41540. _this.OPACITYDIRECTUV = 0;
  41541. _this.OPACITYRGB = false;
  41542. _this.REFLECTION = false;
  41543. _this.EMISSIVE = false;
  41544. _this.EMISSIVEDIRECTUV = 0;
  41545. _this.SPECULAR = false;
  41546. _this.SPECULARDIRECTUV = 0;
  41547. _this.BUMP = false;
  41548. _this.BUMPDIRECTUV = 0;
  41549. _this.PARALLAX = false;
  41550. _this.PARALLAXOCCLUSION = false;
  41551. _this.SPECULAROVERALPHA = false;
  41552. _this.CLIPPLANE = false;
  41553. _this.CLIPPLANE2 = false;
  41554. _this.CLIPPLANE3 = false;
  41555. _this.CLIPPLANE4 = false;
  41556. _this.ALPHATEST = false;
  41557. _this.DEPTHPREPASS = false;
  41558. _this.ALPHAFROMDIFFUSE = false;
  41559. _this.POINTSIZE = false;
  41560. _this.FOG = false;
  41561. _this.SPECULARTERM = false;
  41562. _this.DIFFUSEFRESNEL = false;
  41563. _this.OPACITYFRESNEL = false;
  41564. _this.REFLECTIONFRESNEL = false;
  41565. _this.REFRACTIONFRESNEL = false;
  41566. _this.EMISSIVEFRESNEL = false;
  41567. _this.FRESNEL = false;
  41568. _this.NORMAL = false;
  41569. _this.UV1 = false;
  41570. _this.UV2 = false;
  41571. _this.VERTEXCOLOR = false;
  41572. _this.VERTEXALPHA = false;
  41573. _this.NUM_BONE_INFLUENCERS = 0;
  41574. _this.BonesPerMesh = 0;
  41575. _this.INSTANCES = false;
  41576. _this.GLOSSINESS = false;
  41577. _this.ROUGHNESS = false;
  41578. _this.EMISSIVEASILLUMINATION = false;
  41579. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41580. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41581. _this.LIGHTMAP = false;
  41582. _this.LIGHTMAPDIRECTUV = 0;
  41583. _this.OBJECTSPACE_NORMALMAP = false;
  41584. _this.USELIGHTMAPASSHADOWMAP = false;
  41585. _this.REFLECTIONMAP_3D = false;
  41586. _this.REFLECTIONMAP_SPHERICAL = false;
  41587. _this.REFLECTIONMAP_PLANAR = false;
  41588. _this.REFLECTIONMAP_CUBIC = false;
  41589. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41590. _this.REFLECTIONMAP_PROJECTION = false;
  41591. _this.REFLECTIONMAP_SKYBOX = false;
  41592. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41593. _this.REFLECTIONMAP_EXPLICIT = false;
  41594. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41595. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41596. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41597. _this.INVERTCUBICMAP = false;
  41598. _this.LOGARITHMICDEPTH = false;
  41599. _this.REFRACTION = false;
  41600. _this.REFRACTIONMAP_3D = false;
  41601. _this.REFLECTIONOVERALPHA = false;
  41602. _this.TWOSIDEDLIGHTING = false;
  41603. _this.SHADOWFLOAT = false;
  41604. _this.MORPHTARGETS = false;
  41605. _this.MORPHTARGETS_NORMAL = false;
  41606. _this.MORPHTARGETS_TANGENT = false;
  41607. _this.NUM_MORPH_INFLUENCERS = 0;
  41608. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41609. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41610. _this.IMAGEPROCESSING = false;
  41611. _this.VIGNETTE = false;
  41612. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41613. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41614. _this.TONEMAPPING = false;
  41615. _this.TONEMAPPING_ACES = false;
  41616. _this.CONTRAST = false;
  41617. _this.COLORCURVES = false;
  41618. _this.COLORGRADING = false;
  41619. _this.COLORGRADING3D = false;
  41620. _this.SAMPLER3DGREENDEPTH = false;
  41621. _this.SAMPLER3DBGRMAP = false;
  41622. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41623. /**
  41624. * If the reflection texture on this material is in linear color space
  41625. * @hidden
  41626. */
  41627. _this.IS_REFLECTION_LINEAR = false;
  41628. /**
  41629. * If the refraction texture on this material is in linear color space
  41630. * @hidden
  41631. */
  41632. _this.IS_REFRACTION_LINEAR = false;
  41633. _this.EXPOSURE = false;
  41634. _this.rebuild();
  41635. return _this;
  41636. }
  41637. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41638. var modes = [
  41639. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41640. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41641. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41642. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41643. ];
  41644. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41645. var mode = modes_1[_i];
  41646. this[mode] = (mode === modeToEnable);
  41647. }
  41648. };
  41649. return StandardMaterialDefines;
  41650. }(BABYLON.MaterialDefines));
  41651. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41652. var StandardMaterial = /** @class */ (function (_super) {
  41653. __extends(StandardMaterial, _super);
  41654. function StandardMaterial(name, scene) {
  41655. var _this = _super.call(this, name, scene) || this;
  41656. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41657. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41658. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41659. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41660. _this.specularPower = 64;
  41661. _this._useAlphaFromDiffuseTexture = false;
  41662. _this._useEmissiveAsIllumination = false;
  41663. _this._linkEmissiveWithDiffuse = false;
  41664. _this._useSpecularOverAlpha = false;
  41665. _this._useReflectionOverAlpha = false;
  41666. _this._disableLighting = false;
  41667. _this._useObjectSpaceNormalMap = false;
  41668. _this._useParallax = false;
  41669. _this._useParallaxOcclusion = false;
  41670. _this.parallaxScaleBias = 0.05;
  41671. _this._roughness = 0;
  41672. _this.indexOfRefraction = 0.98;
  41673. _this.invertRefractionY = true;
  41674. /**
  41675. * Defines the alpha limits in alpha test mode
  41676. */
  41677. _this.alphaCutOff = 0.4;
  41678. _this._useLightmapAsShadowmap = false;
  41679. _this._useReflectionFresnelFromSpecular = false;
  41680. _this._useGlossinessFromSpecularMapAlpha = false;
  41681. _this._maxSimultaneousLights = 4;
  41682. /**
  41683. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41684. */
  41685. _this._invertNormalMapX = false;
  41686. /**
  41687. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41688. */
  41689. _this._invertNormalMapY = false;
  41690. /**
  41691. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41692. */
  41693. _this._twoSidedLighting = false;
  41694. _this._renderTargets = new BABYLON.SmartArray(16);
  41695. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41696. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41697. // Setup the default processing configuration to the scene.
  41698. _this._attachImageProcessingConfiguration(null);
  41699. _this.getRenderTargetTextures = function () {
  41700. _this._renderTargets.reset();
  41701. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41702. _this._renderTargets.push(_this._reflectionTexture);
  41703. }
  41704. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41705. _this._renderTargets.push(_this._refractionTexture);
  41706. }
  41707. return _this._renderTargets;
  41708. };
  41709. return _this;
  41710. }
  41711. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41712. /**
  41713. * Gets the image processing configuration used either in this material.
  41714. */
  41715. get: function () {
  41716. return this._imageProcessingConfiguration;
  41717. },
  41718. /**
  41719. * Sets the Default image processing configuration used either in the this material.
  41720. *
  41721. * If sets to null, the scene one is in use.
  41722. */
  41723. set: function (value) {
  41724. this._attachImageProcessingConfiguration(value);
  41725. // Ensure the effect will be rebuilt.
  41726. this._markAllSubMeshesAsTexturesDirty();
  41727. },
  41728. enumerable: true,
  41729. configurable: true
  41730. });
  41731. /**
  41732. * Attaches a new image processing configuration to the Standard Material.
  41733. * @param configuration
  41734. */
  41735. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41736. var _this = this;
  41737. if (configuration === this._imageProcessingConfiguration) {
  41738. return;
  41739. }
  41740. // Detaches observer.
  41741. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41742. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41743. }
  41744. // Pick the scene configuration if needed.
  41745. if (!configuration) {
  41746. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41747. }
  41748. else {
  41749. this._imageProcessingConfiguration = configuration;
  41750. }
  41751. // Attaches observer.
  41752. if (this._imageProcessingConfiguration) {
  41753. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41754. _this._markAllSubMeshesAsImageProcessingDirty();
  41755. });
  41756. }
  41757. };
  41758. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41759. /**
  41760. * Gets wether the color curves effect is enabled.
  41761. */
  41762. get: function () {
  41763. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41764. },
  41765. /**
  41766. * Sets wether the color curves effect is enabled.
  41767. */
  41768. set: function (value) {
  41769. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41770. },
  41771. enumerable: true,
  41772. configurable: true
  41773. });
  41774. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41775. /**
  41776. * Gets wether the color grading effect is enabled.
  41777. */
  41778. get: function () {
  41779. return this.imageProcessingConfiguration.colorGradingEnabled;
  41780. },
  41781. /**
  41782. * Gets wether the color grading effect is enabled.
  41783. */
  41784. set: function (value) {
  41785. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41786. },
  41787. enumerable: true,
  41788. configurable: true
  41789. });
  41790. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41791. /**
  41792. * Gets wether tonemapping is enabled or not.
  41793. */
  41794. get: function () {
  41795. return this._imageProcessingConfiguration.toneMappingEnabled;
  41796. },
  41797. /**
  41798. * Sets wether tonemapping is enabled or not
  41799. */
  41800. set: function (value) {
  41801. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41802. },
  41803. enumerable: true,
  41804. configurable: true
  41805. });
  41806. ;
  41807. ;
  41808. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41809. /**
  41810. * The camera exposure used on this material.
  41811. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41812. * This corresponds to a photographic exposure.
  41813. */
  41814. get: function () {
  41815. return this._imageProcessingConfiguration.exposure;
  41816. },
  41817. /**
  41818. * The camera exposure used on this material.
  41819. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41820. * This corresponds to a photographic exposure.
  41821. */
  41822. set: function (value) {
  41823. this._imageProcessingConfiguration.exposure = value;
  41824. },
  41825. enumerable: true,
  41826. configurable: true
  41827. });
  41828. ;
  41829. ;
  41830. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41831. /**
  41832. * Gets The camera contrast used on this material.
  41833. */
  41834. get: function () {
  41835. return this._imageProcessingConfiguration.contrast;
  41836. },
  41837. /**
  41838. * Sets The camera contrast used on this material.
  41839. */
  41840. set: function (value) {
  41841. this._imageProcessingConfiguration.contrast = value;
  41842. },
  41843. enumerable: true,
  41844. configurable: true
  41845. });
  41846. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41847. /**
  41848. * Gets the Color Grading 2D Lookup Texture.
  41849. */
  41850. get: function () {
  41851. return this._imageProcessingConfiguration.colorGradingTexture;
  41852. },
  41853. /**
  41854. * Sets the Color Grading 2D Lookup Texture.
  41855. */
  41856. set: function (value) {
  41857. this._imageProcessingConfiguration.colorGradingTexture = value;
  41858. },
  41859. enumerable: true,
  41860. configurable: true
  41861. });
  41862. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41863. /**
  41864. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41865. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41866. * 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;
  41867. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41868. */
  41869. get: function () {
  41870. return this._imageProcessingConfiguration.colorCurves;
  41871. },
  41872. /**
  41873. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41874. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41875. * 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;
  41876. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41877. */
  41878. set: function (value) {
  41879. this._imageProcessingConfiguration.colorCurves = value;
  41880. },
  41881. enumerable: true,
  41882. configurable: true
  41883. });
  41884. StandardMaterial.prototype.getClassName = function () {
  41885. return "StandardMaterial";
  41886. };
  41887. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41888. get: function () {
  41889. return this._useLogarithmicDepth;
  41890. },
  41891. set: function (value) {
  41892. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41893. this._markAllSubMeshesAsMiscDirty();
  41894. },
  41895. enumerable: true,
  41896. configurable: true
  41897. });
  41898. StandardMaterial.prototype.needAlphaBlending = function () {
  41899. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41900. };
  41901. StandardMaterial.prototype.needAlphaTesting = function () {
  41902. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41903. };
  41904. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41905. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41906. };
  41907. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41908. return this._diffuseTexture;
  41909. };
  41910. /**
  41911. * Child classes can use it to update shaders
  41912. */
  41913. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41914. if (useInstances === void 0) { useInstances = false; }
  41915. if (subMesh.effect && this.isFrozen) {
  41916. if (this._wasPreviouslyReady) {
  41917. return true;
  41918. }
  41919. }
  41920. if (!subMesh._materialDefines) {
  41921. subMesh._materialDefines = new StandardMaterialDefines();
  41922. }
  41923. var scene = this.getScene();
  41924. var defines = subMesh._materialDefines;
  41925. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41926. if (defines._renderId === scene.getRenderId()) {
  41927. return true;
  41928. }
  41929. }
  41930. var engine = scene.getEngine();
  41931. // Lights
  41932. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41933. // Textures
  41934. if (defines._areTexturesDirty) {
  41935. defines._needUVs = false;
  41936. defines.MAINUV1 = false;
  41937. defines.MAINUV2 = false;
  41938. if (scene.texturesEnabled) {
  41939. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41940. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41941. return false;
  41942. }
  41943. else {
  41944. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41945. }
  41946. }
  41947. else {
  41948. defines.DIFFUSE = false;
  41949. }
  41950. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41951. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41952. return false;
  41953. }
  41954. else {
  41955. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41956. }
  41957. }
  41958. else {
  41959. defines.AMBIENT = false;
  41960. }
  41961. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41962. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41963. return false;
  41964. }
  41965. else {
  41966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41967. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41968. }
  41969. }
  41970. else {
  41971. defines.OPACITY = false;
  41972. }
  41973. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41974. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41975. return false;
  41976. }
  41977. else {
  41978. defines._needNormals = true;
  41979. defines.REFLECTION = true;
  41980. defines.ROUGHNESS = (this._roughness > 0);
  41981. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41982. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41983. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41984. switch (this._reflectionTexture.coordinatesMode) {
  41985. case BABYLON.Texture.EXPLICIT_MODE:
  41986. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41987. break;
  41988. case BABYLON.Texture.PLANAR_MODE:
  41989. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41990. break;
  41991. case BABYLON.Texture.PROJECTION_MODE:
  41992. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41993. break;
  41994. case BABYLON.Texture.SKYBOX_MODE:
  41995. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41996. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41997. break;
  41998. case BABYLON.Texture.SPHERICAL_MODE:
  41999. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42000. break;
  42001. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42002. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42003. break;
  42004. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42005. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42006. break;
  42007. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42008. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42009. break;
  42010. case BABYLON.Texture.CUBIC_MODE:
  42011. case BABYLON.Texture.INVCUBIC_MODE:
  42012. default:
  42013. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42014. break;
  42015. }
  42016. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42017. }
  42018. }
  42019. else {
  42020. defines.REFLECTION = false;
  42021. }
  42022. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42023. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42024. return false;
  42025. }
  42026. else {
  42027. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42028. }
  42029. }
  42030. else {
  42031. defines.EMISSIVE = false;
  42032. }
  42033. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42034. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42035. return false;
  42036. }
  42037. else {
  42038. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42039. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42040. }
  42041. }
  42042. else {
  42043. defines.LIGHTMAP = false;
  42044. }
  42045. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42046. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42047. return false;
  42048. }
  42049. else {
  42050. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42051. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42052. }
  42053. }
  42054. else {
  42055. defines.SPECULAR = false;
  42056. }
  42057. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42058. // Bump texure can not be not blocking.
  42059. if (!this._bumpTexture.isReady()) {
  42060. return false;
  42061. }
  42062. else {
  42063. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42064. defines.PARALLAX = this._useParallax;
  42065. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42066. }
  42067. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42068. }
  42069. else {
  42070. defines.BUMP = false;
  42071. }
  42072. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42073. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42074. return false;
  42075. }
  42076. else {
  42077. defines._needUVs = true;
  42078. defines.REFRACTION = true;
  42079. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42080. }
  42081. }
  42082. else {
  42083. defines.REFRACTION = false;
  42084. }
  42085. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42086. }
  42087. else {
  42088. defines.DIFFUSE = false;
  42089. defines.AMBIENT = false;
  42090. defines.OPACITY = false;
  42091. defines.REFLECTION = false;
  42092. defines.EMISSIVE = false;
  42093. defines.LIGHTMAP = false;
  42094. defines.BUMP = false;
  42095. defines.REFRACTION = false;
  42096. }
  42097. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42098. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42099. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42100. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42101. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42102. }
  42103. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42104. if (!this._imageProcessingConfiguration.isReady()) {
  42105. return false;
  42106. }
  42107. this._imageProcessingConfiguration.prepareDefines(defines);
  42108. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42109. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42110. }
  42111. if (defines._areFresnelDirty) {
  42112. if (StandardMaterial.FresnelEnabled) {
  42113. // Fresnel
  42114. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42115. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42116. this._reflectionFresnelParameters) {
  42117. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42118. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42119. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42120. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42121. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42122. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42123. defines._needNormals = true;
  42124. defines.FRESNEL = true;
  42125. }
  42126. }
  42127. else {
  42128. defines.FRESNEL = false;
  42129. }
  42130. }
  42131. // Misc.
  42132. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42133. // Attribs
  42134. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42135. // Values that need to be evaluated on every frame
  42136. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42137. // Get correct effect
  42138. if (defines.isDirty) {
  42139. defines.markAsProcessed();
  42140. scene.resetCachedMaterial();
  42141. // Fallbacks
  42142. var fallbacks = new BABYLON.EffectFallbacks();
  42143. if (defines.REFLECTION) {
  42144. fallbacks.addFallback(0, "REFLECTION");
  42145. }
  42146. if (defines.SPECULAR) {
  42147. fallbacks.addFallback(0, "SPECULAR");
  42148. }
  42149. if (defines.BUMP) {
  42150. fallbacks.addFallback(0, "BUMP");
  42151. }
  42152. if (defines.PARALLAX) {
  42153. fallbacks.addFallback(1, "PARALLAX");
  42154. }
  42155. if (defines.PARALLAXOCCLUSION) {
  42156. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42157. }
  42158. if (defines.SPECULAROVERALPHA) {
  42159. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42160. }
  42161. if (defines.FOG) {
  42162. fallbacks.addFallback(1, "FOG");
  42163. }
  42164. if (defines.POINTSIZE) {
  42165. fallbacks.addFallback(0, "POINTSIZE");
  42166. }
  42167. if (defines.LOGARITHMICDEPTH) {
  42168. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42169. }
  42170. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42171. if (defines.SPECULARTERM) {
  42172. fallbacks.addFallback(0, "SPECULARTERM");
  42173. }
  42174. if (defines.DIFFUSEFRESNEL) {
  42175. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42176. }
  42177. if (defines.OPACITYFRESNEL) {
  42178. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42179. }
  42180. if (defines.REFLECTIONFRESNEL) {
  42181. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42182. }
  42183. if (defines.EMISSIVEFRESNEL) {
  42184. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42185. }
  42186. if (defines.FRESNEL) {
  42187. fallbacks.addFallback(4, "FRESNEL");
  42188. }
  42189. //Attributes
  42190. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42191. if (defines.NORMAL) {
  42192. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42193. }
  42194. if (defines.UV1) {
  42195. attribs.push(BABYLON.VertexBuffer.UVKind);
  42196. }
  42197. if (defines.UV2) {
  42198. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42199. }
  42200. if (defines.VERTEXCOLOR) {
  42201. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42202. }
  42203. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42204. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42205. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42206. var shaderName = "default";
  42207. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42208. "vFogInfos", "vFogColor", "pointSize",
  42209. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42210. "mBones",
  42211. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42212. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42213. "vReflectionPosition", "vReflectionSize",
  42214. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42215. ];
  42216. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42217. var uniformBuffers = ["Material", "Scene"];
  42218. if (BABYLON.ImageProcessingConfiguration) {
  42219. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42220. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42221. }
  42222. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42223. uniformsNames: uniforms,
  42224. uniformBuffersNames: uniformBuffers,
  42225. samplers: samplers,
  42226. defines: defines,
  42227. maxSimultaneousLights: this._maxSimultaneousLights
  42228. });
  42229. if (this.customShaderNameResolve) {
  42230. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42231. }
  42232. var join = defines.toString();
  42233. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42234. attributes: attribs,
  42235. uniformsNames: uniforms,
  42236. uniformBuffersNames: uniformBuffers,
  42237. samplers: samplers,
  42238. defines: join,
  42239. fallbacks: fallbacks,
  42240. onCompiled: this.onCompiled,
  42241. onError: this.onError,
  42242. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42243. }, engine), defines);
  42244. this.buildUniformLayout();
  42245. }
  42246. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42247. return false;
  42248. }
  42249. defines._renderId = scene.getRenderId();
  42250. this._wasPreviouslyReady = true;
  42251. return true;
  42252. };
  42253. StandardMaterial.prototype.buildUniformLayout = function () {
  42254. // Order is important !
  42255. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42256. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42257. this._uniformBuffer.addUniform("opacityParts", 4);
  42258. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42259. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42260. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42261. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42262. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42263. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42264. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42265. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42266. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42267. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42268. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42269. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42270. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42271. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42272. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42273. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42274. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42275. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42276. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42277. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42278. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42279. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42280. this._uniformBuffer.addUniform("specularMatrix", 16);
  42281. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42282. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42283. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42284. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42285. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42286. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42287. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42288. this._uniformBuffer.addUniform("pointSize", 1);
  42289. this._uniformBuffer.create();
  42290. };
  42291. StandardMaterial.prototype.unbind = function () {
  42292. if (this._activeEffect) {
  42293. var needFlag = false;
  42294. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42295. this._activeEffect.setTexture("reflection2DSampler", null);
  42296. needFlag = true;
  42297. }
  42298. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42299. this._activeEffect.setTexture("refraction2DSampler", null);
  42300. needFlag = true;
  42301. }
  42302. if (needFlag) {
  42303. this._markAllSubMeshesAsTexturesDirty();
  42304. }
  42305. }
  42306. _super.prototype.unbind.call(this);
  42307. };
  42308. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42309. var scene = this.getScene();
  42310. var defines = subMesh._materialDefines;
  42311. if (!defines) {
  42312. return;
  42313. }
  42314. var effect = subMesh.effect;
  42315. if (!effect) {
  42316. return;
  42317. }
  42318. this._activeEffect = effect;
  42319. // Matrices
  42320. this.bindOnlyWorldMatrix(world);
  42321. // Normal Matrix
  42322. if (defines.OBJECTSPACE_NORMALMAP) {
  42323. world.toNormalMatrix(this._normalMatrix);
  42324. this.bindOnlyNormalMatrix(this._normalMatrix);
  42325. }
  42326. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42327. // Bones
  42328. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42329. if (mustRebind) {
  42330. this._uniformBuffer.bindToEffect(effect, "Material");
  42331. this.bindViewProjection(effect);
  42332. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42333. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42334. // Fresnel
  42335. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42336. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42337. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42338. }
  42339. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42340. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42341. }
  42342. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42343. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42344. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42345. }
  42346. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42347. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42348. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42349. }
  42350. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42351. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42352. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42353. }
  42354. }
  42355. // Textures
  42356. if (scene.texturesEnabled) {
  42357. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42358. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42359. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42360. if (this._diffuseTexture.hasAlpha) {
  42361. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42362. }
  42363. }
  42364. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42365. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42366. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42367. }
  42368. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42369. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42370. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42371. }
  42372. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42373. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42374. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42375. if (this._reflectionTexture.boundingBoxSize) {
  42376. var cubeTexture = this._reflectionTexture;
  42377. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42378. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42379. }
  42380. }
  42381. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42382. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42383. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42384. }
  42385. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42386. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42387. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42388. }
  42389. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42390. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42391. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42392. }
  42393. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42394. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42395. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42396. if (scene._mirroredCameraPosition) {
  42397. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42398. }
  42399. else {
  42400. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42401. }
  42402. }
  42403. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42404. var depth = 1.0;
  42405. if (!this._refractionTexture.isCube) {
  42406. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42407. if (this._refractionTexture.depth) {
  42408. depth = this._refractionTexture.depth;
  42409. }
  42410. }
  42411. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42412. }
  42413. }
  42414. // Point size
  42415. if (this.pointsCloud) {
  42416. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42417. }
  42418. if (defines.SPECULARTERM) {
  42419. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42420. }
  42421. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42422. // Diffuse
  42423. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42424. }
  42425. // Textures
  42426. if (scene.texturesEnabled) {
  42427. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42428. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42429. }
  42430. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42431. effect.setTexture("ambientSampler", this._ambientTexture);
  42432. }
  42433. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42434. effect.setTexture("opacitySampler", this._opacityTexture);
  42435. }
  42436. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42437. if (this._reflectionTexture.isCube) {
  42438. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42439. }
  42440. else {
  42441. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42442. }
  42443. }
  42444. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42445. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42446. }
  42447. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42448. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42449. }
  42450. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42451. effect.setTexture("specularSampler", this._specularTexture);
  42452. }
  42453. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42454. effect.setTexture("bumpSampler", this._bumpTexture);
  42455. }
  42456. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42457. var depth = 1.0;
  42458. if (this._refractionTexture.isCube) {
  42459. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42460. }
  42461. else {
  42462. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42463. }
  42464. }
  42465. }
  42466. // Clip plane
  42467. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42468. // Colors
  42469. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42470. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42471. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42472. }
  42473. if (mustRebind || !this.isFrozen) {
  42474. // Lights
  42475. if (scene.lightsEnabled && !this._disableLighting) {
  42476. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42477. }
  42478. // View
  42479. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42480. this.bindView(effect);
  42481. }
  42482. // Fog
  42483. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42484. // Morph targets
  42485. if (defines.NUM_MORPH_INFLUENCERS) {
  42486. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42487. }
  42488. // Log. depth
  42489. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42490. // image processing
  42491. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42492. this._imageProcessingConfiguration.bind(this._activeEffect);
  42493. }
  42494. }
  42495. this._uniformBuffer.update();
  42496. this._afterBind(mesh, this._activeEffect);
  42497. };
  42498. StandardMaterial.prototype.getAnimatables = function () {
  42499. var results = [];
  42500. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42501. results.push(this._diffuseTexture);
  42502. }
  42503. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42504. results.push(this._ambientTexture);
  42505. }
  42506. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42507. results.push(this._opacityTexture);
  42508. }
  42509. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42510. results.push(this._reflectionTexture);
  42511. }
  42512. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42513. results.push(this._emissiveTexture);
  42514. }
  42515. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42516. results.push(this._specularTexture);
  42517. }
  42518. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42519. results.push(this._bumpTexture);
  42520. }
  42521. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42522. results.push(this._lightmapTexture);
  42523. }
  42524. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42525. results.push(this._refractionTexture);
  42526. }
  42527. return results;
  42528. };
  42529. StandardMaterial.prototype.getActiveTextures = function () {
  42530. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42531. if (this._diffuseTexture) {
  42532. activeTextures.push(this._diffuseTexture);
  42533. }
  42534. if (this._ambientTexture) {
  42535. activeTextures.push(this._ambientTexture);
  42536. }
  42537. if (this._opacityTexture) {
  42538. activeTextures.push(this._opacityTexture);
  42539. }
  42540. if (this._reflectionTexture) {
  42541. activeTextures.push(this._reflectionTexture);
  42542. }
  42543. if (this._emissiveTexture) {
  42544. activeTextures.push(this._emissiveTexture);
  42545. }
  42546. if (this._specularTexture) {
  42547. activeTextures.push(this._specularTexture);
  42548. }
  42549. if (this._bumpTexture) {
  42550. activeTextures.push(this._bumpTexture);
  42551. }
  42552. if (this._lightmapTexture) {
  42553. activeTextures.push(this._lightmapTexture);
  42554. }
  42555. if (this._refractionTexture) {
  42556. activeTextures.push(this._refractionTexture);
  42557. }
  42558. return activeTextures;
  42559. };
  42560. StandardMaterial.prototype.hasTexture = function (texture) {
  42561. if (_super.prototype.hasTexture.call(this, texture)) {
  42562. return true;
  42563. }
  42564. if (this._diffuseTexture === texture) {
  42565. return true;
  42566. }
  42567. if (this._ambientTexture === texture) {
  42568. return true;
  42569. }
  42570. if (this._opacityTexture === texture) {
  42571. return true;
  42572. }
  42573. if (this._reflectionTexture === texture) {
  42574. return true;
  42575. }
  42576. if (this._emissiveTexture === texture) {
  42577. return true;
  42578. }
  42579. if (this._specularTexture === texture) {
  42580. return true;
  42581. }
  42582. if (this._bumpTexture === texture) {
  42583. return true;
  42584. }
  42585. if (this._lightmapTexture === texture) {
  42586. return true;
  42587. }
  42588. if (this._refractionTexture === texture) {
  42589. return true;
  42590. }
  42591. return false;
  42592. };
  42593. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42594. if (forceDisposeTextures) {
  42595. if (this._diffuseTexture) {
  42596. this._diffuseTexture.dispose();
  42597. }
  42598. if (this._ambientTexture) {
  42599. this._ambientTexture.dispose();
  42600. }
  42601. if (this._opacityTexture) {
  42602. this._opacityTexture.dispose();
  42603. }
  42604. if (this._reflectionTexture) {
  42605. this._reflectionTexture.dispose();
  42606. }
  42607. if (this._emissiveTexture) {
  42608. this._emissiveTexture.dispose();
  42609. }
  42610. if (this._specularTexture) {
  42611. this._specularTexture.dispose();
  42612. }
  42613. if (this._bumpTexture) {
  42614. this._bumpTexture.dispose();
  42615. }
  42616. if (this._lightmapTexture) {
  42617. this._lightmapTexture.dispose();
  42618. }
  42619. if (this._refractionTexture) {
  42620. this._refractionTexture.dispose();
  42621. }
  42622. }
  42623. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42624. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42625. }
  42626. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42627. };
  42628. StandardMaterial.prototype.clone = function (name) {
  42629. var _this = this;
  42630. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42631. result.name = name;
  42632. result.id = name;
  42633. return result;
  42634. };
  42635. StandardMaterial.prototype.serialize = function () {
  42636. return BABYLON.SerializationHelper.Serialize(this);
  42637. };
  42638. // Statics
  42639. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42640. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42641. };
  42642. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42643. get: function () {
  42644. return StandardMaterial._DiffuseTextureEnabled;
  42645. },
  42646. set: function (value) {
  42647. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42648. return;
  42649. }
  42650. StandardMaterial._DiffuseTextureEnabled = value;
  42651. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42652. },
  42653. enumerable: true,
  42654. configurable: true
  42655. });
  42656. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42657. get: function () {
  42658. return StandardMaterial._AmbientTextureEnabled;
  42659. },
  42660. set: function (value) {
  42661. if (StandardMaterial._AmbientTextureEnabled === value) {
  42662. return;
  42663. }
  42664. StandardMaterial._AmbientTextureEnabled = value;
  42665. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42666. },
  42667. enumerable: true,
  42668. configurable: true
  42669. });
  42670. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42671. get: function () {
  42672. return StandardMaterial._OpacityTextureEnabled;
  42673. },
  42674. set: function (value) {
  42675. if (StandardMaterial._OpacityTextureEnabled === value) {
  42676. return;
  42677. }
  42678. StandardMaterial._OpacityTextureEnabled = value;
  42679. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42680. },
  42681. enumerable: true,
  42682. configurable: true
  42683. });
  42684. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42685. get: function () {
  42686. return StandardMaterial._ReflectionTextureEnabled;
  42687. },
  42688. set: function (value) {
  42689. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42690. return;
  42691. }
  42692. StandardMaterial._ReflectionTextureEnabled = value;
  42693. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42694. },
  42695. enumerable: true,
  42696. configurable: true
  42697. });
  42698. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42699. get: function () {
  42700. return StandardMaterial._EmissiveTextureEnabled;
  42701. },
  42702. set: function (value) {
  42703. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42704. return;
  42705. }
  42706. StandardMaterial._EmissiveTextureEnabled = value;
  42707. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42708. },
  42709. enumerable: true,
  42710. configurable: true
  42711. });
  42712. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42713. get: function () {
  42714. return StandardMaterial._SpecularTextureEnabled;
  42715. },
  42716. set: function (value) {
  42717. if (StandardMaterial._SpecularTextureEnabled === value) {
  42718. return;
  42719. }
  42720. StandardMaterial._SpecularTextureEnabled = value;
  42721. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42722. },
  42723. enumerable: true,
  42724. configurable: true
  42725. });
  42726. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42727. get: function () {
  42728. return StandardMaterial._BumpTextureEnabled;
  42729. },
  42730. set: function (value) {
  42731. if (StandardMaterial._BumpTextureEnabled === value) {
  42732. return;
  42733. }
  42734. StandardMaterial._BumpTextureEnabled = value;
  42735. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42741. get: function () {
  42742. return StandardMaterial._LightmapTextureEnabled;
  42743. },
  42744. set: function (value) {
  42745. if (StandardMaterial._LightmapTextureEnabled === value) {
  42746. return;
  42747. }
  42748. StandardMaterial._LightmapTextureEnabled = value;
  42749. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42750. },
  42751. enumerable: true,
  42752. configurable: true
  42753. });
  42754. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42755. get: function () {
  42756. return StandardMaterial._RefractionTextureEnabled;
  42757. },
  42758. set: function (value) {
  42759. if (StandardMaterial._RefractionTextureEnabled === value) {
  42760. return;
  42761. }
  42762. StandardMaterial._RefractionTextureEnabled = value;
  42763. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42764. },
  42765. enumerable: true,
  42766. configurable: true
  42767. });
  42768. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42769. get: function () {
  42770. return StandardMaterial._ColorGradingTextureEnabled;
  42771. },
  42772. set: function (value) {
  42773. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42774. return;
  42775. }
  42776. StandardMaterial._ColorGradingTextureEnabled = value;
  42777. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42778. },
  42779. enumerable: true,
  42780. configurable: true
  42781. });
  42782. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42783. get: function () {
  42784. return StandardMaterial._FresnelEnabled;
  42785. },
  42786. set: function (value) {
  42787. if (StandardMaterial._FresnelEnabled === value) {
  42788. return;
  42789. }
  42790. StandardMaterial._FresnelEnabled = value;
  42791. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42792. },
  42793. enumerable: true,
  42794. configurable: true
  42795. });
  42796. // Flags used to enable or disable a type of texture for all Standard Materials
  42797. StandardMaterial._DiffuseTextureEnabled = true;
  42798. StandardMaterial._AmbientTextureEnabled = true;
  42799. StandardMaterial._OpacityTextureEnabled = true;
  42800. StandardMaterial._ReflectionTextureEnabled = true;
  42801. StandardMaterial._EmissiveTextureEnabled = true;
  42802. StandardMaterial._SpecularTextureEnabled = true;
  42803. StandardMaterial._BumpTextureEnabled = true;
  42804. StandardMaterial._LightmapTextureEnabled = true;
  42805. StandardMaterial._RefractionTextureEnabled = true;
  42806. StandardMaterial._ColorGradingTextureEnabled = true;
  42807. StandardMaterial._FresnelEnabled = true;
  42808. __decorate([
  42809. BABYLON.serializeAsTexture("diffuseTexture")
  42810. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42811. __decorate([
  42812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42813. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42814. __decorate([
  42815. BABYLON.serializeAsTexture("ambientTexture")
  42816. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42817. __decorate([
  42818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42819. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42820. __decorate([
  42821. BABYLON.serializeAsTexture("opacityTexture")
  42822. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42823. __decorate([
  42824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42825. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42826. __decorate([
  42827. BABYLON.serializeAsTexture("reflectionTexture")
  42828. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42829. __decorate([
  42830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42831. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42832. __decorate([
  42833. BABYLON.serializeAsTexture("emissiveTexture")
  42834. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42835. __decorate([
  42836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42837. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42838. __decorate([
  42839. BABYLON.serializeAsTexture("specularTexture")
  42840. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42841. __decorate([
  42842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42843. ], StandardMaterial.prototype, "specularTexture", void 0);
  42844. __decorate([
  42845. BABYLON.serializeAsTexture("bumpTexture")
  42846. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42847. __decorate([
  42848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42849. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42850. __decorate([
  42851. BABYLON.serializeAsTexture("lightmapTexture")
  42852. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42853. __decorate([
  42854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42855. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42856. __decorate([
  42857. BABYLON.serializeAsTexture("refractionTexture")
  42858. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42859. __decorate([
  42860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42861. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42862. __decorate([
  42863. BABYLON.serializeAsColor3("ambient")
  42864. ], StandardMaterial.prototype, "ambientColor", void 0);
  42865. __decorate([
  42866. BABYLON.serializeAsColor3("diffuse")
  42867. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42868. __decorate([
  42869. BABYLON.serializeAsColor3("specular")
  42870. ], StandardMaterial.prototype, "specularColor", void 0);
  42871. __decorate([
  42872. BABYLON.serializeAsColor3("emissive")
  42873. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42874. __decorate([
  42875. BABYLON.serialize()
  42876. ], StandardMaterial.prototype, "specularPower", void 0);
  42877. __decorate([
  42878. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42879. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42880. __decorate([
  42881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42882. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42883. __decorate([
  42884. BABYLON.serialize("useEmissiveAsIllumination")
  42885. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42886. __decorate([
  42887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42888. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42889. __decorate([
  42890. BABYLON.serialize("linkEmissiveWithDiffuse")
  42891. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42892. __decorate([
  42893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42894. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42895. __decorate([
  42896. BABYLON.serialize("useSpecularOverAlpha")
  42897. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42898. __decorate([
  42899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42900. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42901. __decorate([
  42902. BABYLON.serialize("useReflectionOverAlpha")
  42903. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42904. __decorate([
  42905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42906. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42907. __decorate([
  42908. BABYLON.serialize("disableLighting")
  42909. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42910. __decorate([
  42911. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42912. ], StandardMaterial.prototype, "disableLighting", void 0);
  42913. __decorate([
  42914. BABYLON.serialize("useObjectSpaceNormalMap")
  42915. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42916. __decorate([
  42917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42918. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42919. __decorate([
  42920. BABYLON.serialize("useParallax")
  42921. ], StandardMaterial.prototype, "_useParallax", void 0);
  42922. __decorate([
  42923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42924. ], StandardMaterial.prototype, "useParallax", void 0);
  42925. __decorate([
  42926. BABYLON.serialize("useParallaxOcclusion")
  42927. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42928. __decorate([
  42929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42930. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42931. __decorate([
  42932. BABYLON.serialize()
  42933. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42934. __decorate([
  42935. BABYLON.serialize("roughness")
  42936. ], StandardMaterial.prototype, "_roughness", void 0);
  42937. __decorate([
  42938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42939. ], StandardMaterial.prototype, "roughness", void 0);
  42940. __decorate([
  42941. BABYLON.serialize()
  42942. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42943. __decorate([
  42944. BABYLON.serialize()
  42945. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42946. __decorate([
  42947. BABYLON.serialize()
  42948. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42949. __decorate([
  42950. BABYLON.serialize("useLightmapAsShadowmap")
  42951. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42952. __decorate([
  42953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42954. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42955. __decorate([
  42956. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42957. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42958. __decorate([
  42959. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42960. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42961. __decorate([
  42962. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42963. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42964. __decorate([
  42965. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42966. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42967. __decorate([
  42968. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42969. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42970. __decorate([
  42971. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42972. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42973. __decorate([
  42974. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42975. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42976. __decorate([
  42977. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42978. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42979. __decorate([
  42980. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42981. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42982. __decorate([
  42983. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42984. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42985. __decorate([
  42986. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42987. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42988. __decorate([
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42990. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42991. __decorate([
  42992. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42993. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42994. __decorate([
  42995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42996. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42997. __decorate([
  42998. BABYLON.serialize("maxSimultaneousLights")
  42999. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43000. __decorate([
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43002. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43003. __decorate([
  43004. BABYLON.serialize("invertNormalMapX")
  43005. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43006. __decorate([
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43008. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43009. __decorate([
  43010. BABYLON.serialize("invertNormalMapY")
  43011. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43012. __decorate([
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43014. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43015. __decorate([
  43016. BABYLON.serialize("twoSidedLighting")
  43017. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43018. __decorate([
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43020. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43021. __decorate([
  43022. BABYLON.serialize()
  43023. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43024. return StandardMaterial;
  43025. }(BABYLON.PushMaterial));
  43026. BABYLON.StandardMaterial = StandardMaterial;
  43027. })(BABYLON || (BABYLON = {}));
  43028. //# sourceMappingURL=babylon.standardMaterial.js.map
  43029. var BABYLON;
  43030. (function (BABYLON) {
  43031. /**
  43032. * Class representing spherical polynomial coefficients to the 3rd degree
  43033. */
  43034. var SphericalPolynomial = /** @class */ (function () {
  43035. function SphericalPolynomial() {
  43036. /**
  43037. * The x coefficients of the spherical polynomial
  43038. */
  43039. this.x = BABYLON.Vector3.Zero();
  43040. /**
  43041. * The y coefficients of the spherical polynomial
  43042. */
  43043. this.y = BABYLON.Vector3.Zero();
  43044. /**
  43045. * The z coefficients of the spherical polynomial
  43046. */
  43047. this.z = BABYLON.Vector3.Zero();
  43048. /**
  43049. * The xx coefficients of the spherical polynomial
  43050. */
  43051. this.xx = BABYLON.Vector3.Zero();
  43052. /**
  43053. * The yy coefficients of the spherical polynomial
  43054. */
  43055. this.yy = BABYLON.Vector3.Zero();
  43056. /**
  43057. * The zz coefficients of the spherical polynomial
  43058. */
  43059. this.zz = BABYLON.Vector3.Zero();
  43060. /**
  43061. * The xy coefficients of the spherical polynomial
  43062. */
  43063. this.xy = BABYLON.Vector3.Zero();
  43064. /**
  43065. * The yz coefficients of the spherical polynomial
  43066. */
  43067. this.yz = BABYLON.Vector3.Zero();
  43068. /**
  43069. * The zx coefficients of the spherical polynomial
  43070. */
  43071. this.zx = BABYLON.Vector3.Zero();
  43072. }
  43073. /**
  43074. * Adds an ambient color to the spherical polynomial
  43075. * @param color the color to add
  43076. */
  43077. SphericalPolynomial.prototype.addAmbient = function (color) {
  43078. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43079. this.xx = this.xx.add(colorVector);
  43080. this.yy = this.yy.add(colorVector);
  43081. this.zz = this.zz.add(colorVector);
  43082. };
  43083. /**
  43084. * Scales the spherical polynomial by the given amount
  43085. * @param scale the amount to scale
  43086. */
  43087. SphericalPolynomial.prototype.scale = function (scale) {
  43088. this.x = this.x.scale(scale);
  43089. this.y = this.y.scale(scale);
  43090. this.z = this.z.scale(scale);
  43091. this.xx = this.xx.scale(scale);
  43092. this.yy = this.yy.scale(scale);
  43093. this.zz = this.zz.scale(scale);
  43094. this.yz = this.yz.scale(scale);
  43095. this.zx = this.zx.scale(scale);
  43096. this.xy = this.xy.scale(scale);
  43097. };
  43098. /**
  43099. * Gets the spherical polynomial from harmonics
  43100. * @param harmonics the spherical harmonics
  43101. * @returns the spherical polynomial
  43102. */
  43103. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43104. var result = new SphericalPolynomial();
  43105. result.x = harmonics.l11.scale(1.02333);
  43106. result.y = harmonics.l1_1.scale(1.02333);
  43107. result.z = harmonics.l10.scale(1.02333);
  43108. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43109. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43110. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43111. result.yz = harmonics.l2_1.scale(0.858086);
  43112. result.zx = harmonics.l21.scale(0.858086);
  43113. result.xy = harmonics.l2_2.scale(0.858086);
  43114. result.scale(1.0 / Math.PI);
  43115. return result;
  43116. };
  43117. /**
  43118. * Constructs a spherical polynomial from an array.
  43119. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43120. * @returns the spherical polynomial
  43121. */
  43122. SphericalPolynomial.FromArray = function (data) {
  43123. var sp = new SphericalPolynomial();
  43124. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43125. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43126. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43127. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43128. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43129. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43130. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43131. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43132. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43133. return sp;
  43134. };
  43135. return SphericalPolynomial;
  43136. }());
  43137. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43138. /**
  43139. * Class representing spherical harmonics coefficients to the 3rd degree
  43140. */
  43141. var SphericalHarmonics = /** @class */ (function () {
  43142. function SphericalHarmonics() {
  43143. /**
  43144. * The l0,0 coefficients of the spherical harmonics
  43145. */
  43146. this.l00 = BABYLON.Vector3.Zero();
  43147. /**
  43148. * The l1,-1 coefficients of the spherical harmonics
  43149. */
  43150. this.l1_1 = BABYLON.Vector3.Zero();
  43151. /**
  43152. * The l1,0 coefficients of the spherical harmonics
  43153. */
  43154. this.l10 = BABYLON.Vector3.Zero();
  43155. /**
  43156. * The l1,1 coefficients of the spherical harmonics
  43157. */
  43158. this.l11 = BABYLON.Vector3.Zero();
  43159. /**
  43160. * The l2,-2 coefficients of the spherical harmonics
  43161. */
  43162. this.l2_2 = BABYLON.Vector3.Zero();
  43163. /**
  43164. * The l2,-1 coefficients of the spherical harmonics
  43165. */
  43166. this.l2_1 = BABYLON.Vector3.Zero();
  43167. /**
  43168. * The l2,0 coefficients of the spherical harmonics
  43169. */
  43170. this.l20 = BABYLON.Vector3.Zero();
  43171. /**
  43172. * The l2,1 coefficients of the spherical harmonics
  43173. */
  43174. this.l21 = BABYLON.Vector3.Zero();
  43175. /**
  43176. * The l2,2 coefficients of the spherical harmonics
  43177. */
  43178. this.lL22 = BABYLON.Vector3.Zero();
  43179. }
  43180. /**
  43181. * Adds a light to the spherical harmonics
  43182. * @param direction the direction of the light
  43183. * @param color the color of the light
  43184. * @param deltaSolidAngle the delta solid angle of the light
  43185. */
  43186. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43187. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43188. var c = colorVector.scale(deltaSolidAngle);
  43189. this.l00 = this.l00.add(c.scale(0.282095));
  43190. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43191. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43192. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43193. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43194. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43195. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43196. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43197. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43198. };
  43199. /**
  43200. * Scales the spherical harmonics by the given amount
  43201. * @param scale the amount to scale
  43202. */
  43203. SphericalHarmonics.prototype.scale = function (scale) {
  43204. this.l00 = this.l00.scale(scale);
  43205. this.l1_1 = this.l1_1.scale(scale);
  43206. this.l10 = this.l10.scale(scale);
  43207. this.l11 = this.l11.scale(scale);
  43208. this.l2_2 = this.l2_2.scale(scale);
  43209. this.l2_1 = this.l2_1.scale(scale);
  43210. this.l20 = this.l20.scale(scale);
  43211. this.l21 = this.l21.scale(scale);
  43212. this.lL22 = this.lL22.scale(scale);
  43213. };
  43214. /**
  43215. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43216. *
  43217. * ```
  43218. * E_lm = A_l * L_lm
  43219. * ```
  43220. *
  43221. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43222. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43223. * the scaling factors are given in equation 9.
  43224. */
  43225. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43226. // Constant (Band 0)
  43227. this.l00 = this.l00.scale(3.141593);
  43228. // Linear (Band 1)
  43229. this.l1_1 = this.l1_1.scale(2.094395);
  43230. this.l10 = this.l10.scale(2.094395);
  43231. this.l11 = this.l11.scale(2.094395);
  43232. // Quadratic (Band 2)
  43233. this.l2_2 = this.l2_2.scale(0.785398);
  43234. this.l2_1 = this.l2_1.scale(0.785398);
  43235. this.l20 = this.l20.scale(0.785398);
  43236. this.l21 = this.l21.scale(0.785398);
  43237. this.lL22 = this.lL22.scale(0.785398);
  43238. };
  43239. /**
  43240. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43241. *
  43242. * ```
  43243. * L = (1/pi) * E * rho
  43244. * ```
  43245. *
  43246. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43247. */
  43248. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43249. this.scale(1.0 / Math.PI);
  43250. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43251. // (The pixel shader must apply albedo after texture fetches, etc).
  43252. };
  43253. /**
  43254. * Gets the spherical harmonics from polynomial
  43255. * @param polynomial the spherical polynomial
  43256. * @returns the spherical harmonics
  43257. */
  43258. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43259. var result = new SphericalHarmonics();
  43260. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43261. result.l1_1 = polynomial.y.scale(0.977204);
  43262. result.l10 = polynomial.z.scale(0.977204);
  43263. result.l11 = polynomial.x.scale(0.977204);
  43264. result.l2_2 = polynomial.xy.scale(1.16538);
  43265. result.l2_1 = polynomial.yz.scale(1.16538);
  43266. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43267. result.l21 = polynomial.zx.scale(1.16538);
  43268. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43269. result.scale(Math.PI);
  43270. return result;
  43271. };
  43272. /**
  43273. * Constructs a spherical harmonics from an array.
  43274. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43275. * @returns the spherical harmonics
  43276. */
  43277. SphericalHarmonics.FromArray = function (data) {
  43278. var sh = new SphericalHarmonics();
  43279. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43280. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43281. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43282. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43283. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43284. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43285. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43286. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43287. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43288. return sh;
  43289. };
  43290. return SphericalHarmonics;
  43291. }());
  43292. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43293. })(BABYLON || (BABYLON = {}));
  43294. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43295. var BABYLON;
  43296. (function (BABYLON) {
  43297. var FileFaceOrientation = /** @class */ (function () {
  43298. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43299. this.name = name;
  43300. this.worldAxisForNormal = worldAxisForNormal;
  43301. this.worldAxisForFileX = worldAxisForFileX;
  43302. this.worldAxisForFileY = worldAxisForFileY;
  43303. }
  43304. return FileFaceOrientation;
  43305. }());
  43306. ;
  43307. /**
  43308. * Helper class dealing with the extraction of spherical polynomial dataArray
  43309. * from a cube map.
  43310. */
  43311. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43312. function CubeMapToSphericalPolynomialTools() {
  43313. }
  43314. /**
  43315. * Converts a texture to the according Spherical Polynomial data.
  43316. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43317. *
  43318. * @param texture The texture to extract the information from.
  43319. * @return The Spherical Polynomial data.
  43320. */
  43321. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43322. if (!texture.isCube) {
  43323. // Only supports cube Textures currently.
  43324. return null;
  43325. }
  43326. var size = texture.getSize().width;
  43327. var right = texture.readPixels(0);
  43328. var left = texture.readPixels(1);
  43329. var up;
  43330. var down;
  43331. if (texture.isRenderTarget) {
  43332. up = texture.readPixels(3);
  43333. down = texture.readPixels(2);
  43334. }
  43335. else {
  43336. up = texture.readPixels(2);
  43337. down = texture.readPixels(3);
  43338. }
  43339. var front = texture.readPixels(4);
  43340. var back = texture.readPixels(5);
  43341. var gammaSpace = texture.gammaSpace;
  43342. // Always read as RGBA.
  43343. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43344. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43345. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43346. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43347. }
  43348. var cubeInfo = {
  43349. size: size,
  43350. right: right,
  43351. left: left,
  43352. up: up,
  43353. down: down,
  43354. front: front,
  43355. back: back,
  43356. format: format,
  43357. type: type,
  43358. gammaSpace: gammaSpace,
  43359. };
  43360. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43361. };
  43362. /**
  43363. * Converts a cubemap to the according Spherical Polynomial data.
  43364. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43365. *
  43366. * @param cubeInfo The Cube map to extract the information from.
  43367. * @return The Spherical Polynomial data.
  43368. */
  43369. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43370. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43371. var totalSolidAngle = 0.0;
  43372. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43373. var du = 2.0 / cubeInfo.size;
  43374. var dv = du;
  43375. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43376. var minUV = du * 0.5 - 1.0;
  43377. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43378. var fileFace = this.FileFaces[faceIndex];
  43379. var dataArray = cubeInfo[fileFace.name];
  43380. var v = minUV;
  43381. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43382. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43383. // Because SP is still linear, so summation is fine in that basis.
  43384. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43385. for (var y = 0; y < cubeInfo.size; y++) {
  43386. var u = minUV;
  43387. for (var x = 0; x < cubeInfo.size; x++) {
  43388. // World direction (not normalised)
  43389. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43390. worldDirection.normalize();
  43391. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43392. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43393. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43394. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43395. // Handle Integer types.
  43396. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43397. r /= 255;
  43398. g /= 255;
  43399. b /= 255;
  43400. }
  43401. // Handle Gamma space textures.
  43402. if (cubeInfo.gammaSpace) {
  43403. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43404. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43405. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43406. }
  43407. var color = new BABYLON.Color3(r, g, b);
  43408. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43409. totalSolidAngle += deltaSolidAngle;
  43410. u += du;
  43411. }
  43412. v += dv;
  43413. }
  43414. }
  43415. // Solid angle for entire sphere is 4*pi
  43416. var sphereSolidAngle = 4.0 * Math.PI;
  43417. // Adjust the solid angle to allow for how many faces we processed.
  43418. var facesProcessed = 6.0;
  43419. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43420. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43421. // This is needed because the numerical integration over the cube uses a
  43422. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43423. // and also to compensate for accumulative error due to float precision in the summation.
  43424. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43425. sphericalHarmonics.scale(correctionFactor);
  43426. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43427. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43428. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43429. };
  43430. CubeMapToSphericalPolynomialTools.FileFaces = [
  43431. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43432. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43433. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43434. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43435. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43436. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43437. ];
  43438. return CubeMapToSphericalPolynomialTools;
  43439. }());
  43440. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43441. })(BABYLON || (BABYLON = {}));
  43442. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43443. var BABYLON;
  43444. (function (BABYLON) {
  43445. /**
  43446. * Manages the defines for the PBR Material.
  43447. * @hiddenChildren
  43448. */
  43449. var PBRMaterialDefines = /** @class */ (function (_super) {
  43450. __extends(PBRMaterialDefines, _super);
  43451. /**
  43452. * Initializes the PBR Material defines.
  43453. */
  43454. function PBRMaterialDefines() {
  43455. var _this = _super.call(this) || this;
  43456. _this.PBR = true;
  43457. _this.MAINUV1 = false;
  43458. _this.MAINUV2 = false;
  43459. _this.UV1 = false;
  43460. _this.UV2 = false;
  43461. _this.ALBEDO = false;
  43462. _this.ALBEDODIRECTUV = 0;
  43463. _this.VERTEXCOLOR = false;
  43464. _this.AMBIENT = false;
  43465. _this.AMBIENTDIRECTUV = 0;
  43466. _this.AMBIENTINGRAYSCALE = false;
  43467. _this.OPACITY = false;
  43468. _this.VERTEXALPHA = false;
  43469. _this.OPACITYDIRECTUV = 0;
  43470. _this.OPACITYRGB = false;
  43471. _this.ALPHATEST = false;
  43472. _this.DEPTHPREPASS = false;
  43473. _this.ALPHABLEND = false;
  43474. _this.ALPHAFROMALBEDO = false;
  43475. _this.ALPHATESTVALUE = "0.5";
  43476. _this.SPECULAROVERALPHA = false;
  43477. _this.RADIANCEOVERALPHA = false;
  43478. _this.ALPHAFRESNEL = false;
  43479. _this.LINEARALPHAFRESNEL = false;
  43480. _this.PREMULTIPLYALPHA = false;
  43481. _this.EMISSIVE = false;
  43482. _this.EMISSIVEDIRECTUV = 0;
  43483. _this.REFLECTIVITY = false;
  43484. _this.REFLECTIVITYDIRECTUV = 0;
  43485. _this.SPECULARTERM = false;
  43486. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43487. _this.MICROSURFACEAUTOMATIC = false;
  43488. _this.LODBASEDMICROSFURACE = false;
  43489. _this.MICROSURFACEMAP = false;
  43490. _this.MICROSURFACEMAPDIRECTUV = 0;
  43491. _this.METALLICWORKFLOW = false;
  43492. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43493. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43494. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43495. _this.AOSTOREINMETALMAPRED = false;
  43496. _this.ENVIRONMENTBRDF = false;
  43497. _this.NORMAL = false;
  43498. _this.TANGENT = false;
  43499. _this.BUMP = false;
  43500. _this.BUMPDIRECTUV = 0;
  43501. _this.OBJECTSPACE_NORMALMAP = false;
  43502. _this.PARALLAX = false;
  43503. _this.PARALLAXOCCLUSION = false;
  43504. _this.NORMALXYSCALE = true;
  43505. _this.LIGHTMAP = false;
  43506. _this.LIGHTMAPDIRECTUV = 0;
  43507. _this.USELIGHTMAPASSHADOWMAP = false;
  43508. _this.GAMMALIGHTMAP = false;
  43509. _this.REFLECTION = false;
  43510. _this.REFLECTIONMAP_3D = false;
  43511. _this.REFLECTIONMAP_SPHERICAL = false;
  43512. _this.REFLECTIONMAP_PLANAR = false;
  43513. _this.REFLECTIONMAP_CUBIC = false;
  43514. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43515. _this.REFLECTIONMAP_PROJECTION = false;
  43516. _this.REFLECTIONMAP_SKYBOX = false;
  43517. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43518. _this.REFLECTIONMAP_EXPLICIT = false;
  43519. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43520. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43521. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43522. _this.INVERTCUBICMAP = false;
  43523. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43524. _this.USESPHERICALINVERTEX = false;
  43525. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43526. _this.LODINREFLECTIONALPHA = false;
  43527. _this.GAMMAREFLECTION = false;
  43528. _this.RGBDREFLECTION = false;
  43529. _this.RADIANCEOCCLUSION = false;
  43530. _this.HORIZONOCCLUSION = false;
  43531. _this.REFRACTION = false;
  43532. _this.REFRACTIONMAP_3D = false;
  43533. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43534. _this.LODINREFRACTIONALPHA = false;
  43535. _this.GAMMAREFRACTION = false;
  43536. _this.RGBDREFRACTION = false;
  43537. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43538. _this.INSTANCES = false;
  43539. _this.NUM_BONE_INFLUENCERS = 0;
  43540. _this.BonesPerMesh = 0;
  43541. _this.NONUNIFORMSCALING = false;
  43542. _this.MORPHTARGETS = false;
  43543. _this.MORPHTARGETS_NORMAL = false;
  43544. _this.MORPHTARGETS_TANGENT = false;
  43545. _this.NUM_MORPH_INFLUENCERS = 0;
  43546. _this.IMAGEPROCESSING = false;
  43547. _this.VIGNETTE = false;
  43548. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43549. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43550. _this.TONEMAPPING = false;
  43551. _this.TONEMAPPING_ACES = false;
  43552. _this.CONTRAST = false;
  43553. _this.COLORCURVES = false;
  43554. _this.COLORGRADING = false;
  43555. _this.COLORGRADING3D = false;
  43556. _this.SAMPLER3DGREENDEPTH = false;
  43557. _this.SAMPLER3DBGRMAP = false;
  43558. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43559. _this.EXPOSURE = false;
  43560. _this.USEPHYSICALLIGHTFALLOFF = false;
  43561. _this.USEGLTFLIGHTFALLOFF = false;
  43562. _this.TWOSIDEDLIGHTING = false;
  43563. _this.SHADOWFLOAT = false;
  43564. _this.CLIPPLANE = false;
  43565. _this.CLIPPLANE2 = false;
  43566. _this.CLIPPLANE3 = false;
  43567. _this.CLIPPLANE4 = false;
  43568. _this.POINTSIZE = false;
  43569. _this.FOG = false;
  43570. _this.LOGARITHMICDEPTH = false;
  43571. _this.FORCENORMALFORWARD = false;
  43572. _this.SPECULARAA = false;
  43573. _this.UNLIT = false;
  43574. _this.rebuild();
  43575. return _this;
  43576. }
  43577. /**
  43578. * Resets the PBR Material defines.
  43579. */
  43580. PBRMaterialDefines.prototype.reset = function () {
  43581. _super.prototype.reset.call(this);
  43582. this.ALPHATESTVALUE = "0.5";
  43583. this.PBR = true;
  43584. };
  43585. return PBRMaterialDefines;
  43586. }(BABYLON.MaterialDefines));
  43587. /**
  43588. * The Physically based material base class of BJS.
  43589. *
  43590. * This offers the main features of a standard PBR material.
  43591. * For more information, please refer to the documentation :
  43592. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43593. */
  43594. var PBRBaseMaterial = /** @class */ (function (_super) {
  43595. __extends(PBRBaseMaterial, _super);
  43596. /**
  43597. * Instantiates a new PBRMaterial instance.
  43598. *
  43599. * @param name The material name
  43600. * @param scene The scene the material will be use in.
  43601. */
  43602. function PBRBaseMaterial(name, scene) {
  43603. var _this = _super.call(this, name, scene) || this;
  43604. /**
  43605. * Intensity of the direct lights e.g. the four lights available in your scene.
  43606. * This impacts both the direct diffuse and specular highlights.
  43607. */
  43608. _this._directIntensity = 1.0;
  43609. /**
  43610. * Intensity of the emissive part of the material.
  43611. * This helps controlling the emissive effect without modifying the emissive color.
  43612. */
  43613. _this._emissiveIntensity = 1.0;
  43614. /**
  43615. * Intensity of the environment e.g. how much the environment will light the object
  43616. * either through harmonics for rough material or through the refelction for shiny ones.
  43617. */
  43618. _this._environmentIntensity = 1.0;
  43619. /**
  43620. * This is a special control allowing the reduction of the specular highlights coming from the
  43621. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43622. */
  43623. _this._specularIntensity = 1.0;
  43624. /**
  43625. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43626. */
  43627. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43628. /**
  43629. * Debug Control allowing disabling the bump map on this material.
  43630. */
  43631. _this._disableBumpMap = false;
  43632. /**
  43633. * AKA Occlusion Texture Intensity in other nomenclature.
  43634. */
  43635. _this._ambientTextureStrength = 1.0;
  43636. /**
  43637. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43638. * 1 means it completely occludes it
  43639. * 0 mean it has no impact
  43640. */
  43641. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43642. /**
  43643. * The color of a material in ambient lighting.
  43644. */
  43645. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43646. /**
  43647. * AKA Diffuse Color in other nomenclature.
  43648. */
  43649. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43650. /**
  43651. * AKA Specular Color in other nomenclature.
  43652. */
  43653. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43654. /**
  43655. * The color applied when light is reflected from a material.
  43656. */
  43657. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43658. /**
  43659. * The color applied when light is emitted from a material.
  43660. */
  43661. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43662. /**
  43663. * AKA Glossiness in other nomenclature.
  43664. */
  43665. _this._microSurface = 0.9;
  43666. /**
  43667. * source material index of refraction (IOR)' / 'destination material IOR.
  43668. */
  43669. _this._indexOfRefraction = 0.66;
  43670. /**
  43671. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43672. */
  43673. _this._invertRefractionY = false;
  43674. /**
  43675. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43676. * Materials half opaque for instance using refraction could benefit from this control.
  43677. */
  43678. _this._linkRefractionWithTransparency = false;
  43679. /**
  43680. * Specifies that the material will use the light map as a show map.
  43681. */
  43682. _this._useLightmapAsShadowmap = false;
  43683. /**
  43684. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43685. * makes the reflect vector face the model (under horizon).
  43686. */
  43687. _this._useHorizonOcclusion = true;
  43688. /**
  43689. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43690. * too much the area relying on ambient texture to define their ambient occlusion.
  43691. */
  43692. _this._useRadianceOcclusion = true;
  43693. /**
  43694. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43695. */
  43696. _this._useAlphaFromAlbedoTexture = false;
  43697. /**
  43698. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43699. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43700. */
  43701. _this._useSpecularOverAlpha = true;
  43702. /**
  43703. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43704. */
  43705. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43706. /**
  43707. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43708. */
  43709. _this._useRoughnessFromMetallicTextureAlpha = true;
  43710. /**
  43711. * Specifies if the metallic texture contains the roughness information in its green channel.
  43712. */
  43713. _this._useRoughnessFromMetallicTextureGreen = false;
  43714. /**
  43715. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43716. */
  43717. _this._useMetallnessFromMetallicTextureBlue = false;
  43718. /**
  43719. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43720. */
  43721. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43722. /**
  43723. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43724. */
  43725. _this._useAmbientInGrayScale = false;
  43726. /**
  43727. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43728. * The material will try to infer what glossiness each pixel should be.
  43729. */
  43730. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43731. /**
  43732. * Defines the falloff type used in this material.
  43733. * It by default is Physical.
  43734. */
  43735. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43736. /**
  43737. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43738. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43739. */
  43740. _this._useRadianceOverAlpha = true;
  43741. /**
  43742. * Allows using an object space normal map (instead of tangent space).
  43743. */
  43744. _this._useObjectSpaceNormalMap = false;
  43745. /**
  43746. * Allows using the bump map in parallax mode.
  43747. */
  43748. _this._useParallax = false;
  43749. /**
  43750. * Allows using the bump map in parallax occlusion mode.
  43751. */
  43752. _this._useParallaxOcclusion = false;
  43753. /**
  43754. * Controls the scale bias of the parallax mode.
  43755. */
  43756. _this._parallaxScaleBias = 0.05;
  43757. /**
  43758. * If sets to true, disables all the lights affecting the material.
  43759. */
  43760. _this._disableLighting = false;
  43761. /**
  43762. * Number of Simultaneous lights allowed on the material.
  43763. */
  43764. _this._maxSimultaneousLights = 4;
  43765. /**
  43766. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43767. */
  43768. _this._invertNormalMapX = false;
  43769. /**
  43770. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43771. */
  43772. _this._invertNormalMapY = false;
  43773. /**
  43774. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43775. */
  43776. _this._twoSidedLighting = false;
  43777. /**
  43778. * Defines the alpha limits in alpha test mode.
  43779. */
  43780. _this._alphaCutOff = 0.4;
  43781. /**
  43782. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43783. */
  43784. _this._forceAlphaTest = false;
  43785. /**
  43786. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43787. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43788. */
  43789. _this._useAlphaFresnel = false;
  43790. /**
  43791. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43792. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43793. */
  43794. _this._useLinearAlphaFresnel = false;
  43795. /**
  43796. * The transparency mode of the material.
  43797. */
  43798. _this._transparencyMode = null;
  43799. /**
  43800. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43801. * from cos thetav and roughness:
  43802. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43803. */
  43804. _this._environmentBRDFTexture = null;
  43805. /**
  43806. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43807. */
  43808. _this._forceIrradianceInFragment = false;
  43809. /**
  43810. * Force normal to face away from face.
  43811. */
  43812. _this._forceNormalForward = false;
  43813. /**
  43814. * Enables specular anti aliasing in the PBR shader.
  43815. * It will both interacts on the Geometry for analytical and IBL lighting.
  43816. * It also prefilter the roughness map based on the bump values.
  43817. */
  43818. _this._enableSpecularAntiAliasing = false;
  43819. /**
  43820. * Stores the available render targets.
  43821. */
  43822. _this._renderTargets = new BABYLON.SmartArray(16);
  43823. /**
  43824. * Sets the global ambient color for the material used in lighting calculations.
  43825. */
  43826. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43827. /**
  43828. * If set to true, no lighting calculations will be applied.
  43829. */
  43830. _this._unlit = false;
  43831. // Setup the default processing configuration to the scene.
  43832. _this._attachImageProcessingConfiguration(null);
  43833. _this.getRenderTargetTextures = function () {
  43834. _this._renderTargets.reset();
  43835. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43836. _this._renderTargets.push(_this._reflectionTexture);
  43837. }
  43838. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43839. _this._renderTargets.push(_this._refractionTexture);
  43840. }
  43841. return _this._renderTargets;
  43842. };
  43843. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43844. return _this;
  43845. }
  43846. /**
  43847. * Attaches a new image processing configuration to the PBR Material.
  43848. * @param configuration
  43849. */
  43850. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43851. var _this = this;
  43852. if (configuration === this._imageProcessingConfiguration) {
  43853. return;
  43854. }
  43855. // Detaches observer.
  43856. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43857. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43858. }
  43859. // Pick the scene configuration if needed.
  43860. if (!configuration) {
  43861. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43862. }
  43863. else {
  43864. this._imageProcessingConfiguration = configuration;
  43865. }
  43866. // Attaches observer.
  43867. if (this._imageProcessingConfiguration) {
  43868. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43869. _this._markAllSubMeshesAsImageProcessingDirty();
  43870. });
  43871. }
  43872. };
  43873. /**
  43874. * Gets the name of the material class.
  43875. */
  43876. PBRBaseMaterial.prototype.getClassName = function () {
  43877. return "PBRBaseMaterial";
  43878. };
  43879. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43880. /**
  43881. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43882. */
  43883. get: function () {
  43884. return this._useLogarithmicDepth;
  43885. },
  43886. /**
  43887. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43888. */
  43889. set: function (value) {
  43890. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43891. },
  43892. enumerable: true,
  43893. configurable: true
  43894. });
  43895. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43896. /**
  43897. * Gets the current transparency mode.
  43898. */
  43899. get: function () {
  43900. return this._transparencyMode;
  43901. },
  43902. /**
  43903. * Sets the transparency mode of the material.
  43904. *
  43905. * | Value | Type | Description |
  43906. * | ----- | ----------------------------------- | ----------- |
  43907. * | 0 | OPAQUE | |
  43908. * | 1 | ALPHATEST | |
  43909. * | 2 | ALPHABLEND | |
  43910. * | 3 | ALPHATESTANDBLEND | |
  43911. *
  43912. */
  43913. set: function (value) {
  43914. if (this._transparencyMode === value) {
  43915. return;
  43916. }
  43917. this._transparencyMode = value;
  43918. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43919. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43920. },
  43921. enumerable: true,
  43922. configurable: true
  43923. });
  43924. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43925. /**
  43926. * Returns true if alpha blending should be disabled.
  43927. */
  43928. get: function () {
  43929. return (this._linkRefractionWithTransparency ||
  43930. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43931. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43932. },
  43933. enumerable: true,
  43934. configurable: true
  43935. });
  43936. /**
  43937. * Specifies whether or not this material should be rendered in alpha blend mode.
  43938. */
  43939. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43940. if (this._disableAlphaBlending) {
  43941. return false;
  43942. }
  43943. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43944. };
  43945. /**
  43946. * Specifies if the mesh will require alpha blending.
  43947. * @param mesh - BJS mesh.
  43948. */
  43949. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43950. if (this._disableAlphaBlending) {
  43951. return false;
  43952. }
  43953. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43954. };
  43955. /**
  43956. * Specifies whether or not this material should be rendered in alpha test mode.
  43957. */
  43958. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43959. if (this._forceAlphaTest) {
  43960. return true;
  43961. }
  43962. if (this._linkRefractionWithTransparency) {
  43963. return false;
  43964. }
  43965. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43966. };
  43967. /**
  43968. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43969. */
  43970. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43971. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43972. };
  43973. /**
  43974. * Gets the texture used for the alpha test.
  43975. */
  43976. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43977. return this._albedoTexture;
  43978. };
  43979. /**
  43980. * Specifies that the submesh is ready to be used.
  43981. * @param mesh - BJS mesh.
  43982. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43983. * @param useInstances - Specifies that instances should be used.
  43984. * @returns - boolean indicating that the submesh is ready or not.
  43985. */
  43986. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43987. if (subMesh.effect && this.isFrozen) {
  43988. if (this._wasPreviouslyReady) {
  43989. return true;
  43990. }
  43991. }
  43992. if (!subMesh._materialDefines) {
  43993. subMesh._materialDefines = new PBRMaterialDefines();
  43994. }
  43995. var defines = subMesh._materialDefines;
  43996. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43997. if (defines._renderId === this.getScene().getRenderId()) {
  43998. return true;
  43999. }
  44000. }
  44001. var scene = this.getScene();
  44002. var engine = scene.getEngine();
  44003. if (defines._areTexturesDirty) {
  44004. if (scene.texturesEnabled) {
  44005. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44006. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44007. return false;
  44008. }
  44009. }
  44010. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44011. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44012. return false;
  44013. }
  44014. }
  44015. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44016. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44017. return false;
  44018. }
  44019. }
  44020. var reflectionTexture = this._getReflectionTexture();
  44021. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44022. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44023. return false;
  44024. }
  44025. }
  44026. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44027. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44028. return false;
  44029. }
  44030. }
  44031. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44032. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44033. return false;
  44034. }
  44035. }
  44036. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44037. if (this._metallicTexture) {
  44038. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44039. return false;
  44040. }
  44041. }
  44042. else if (this._reflectivityTexture) {
  44043. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44044. return false;
  44045. }
  44046. }
  44047. if (this._microSurfaceTexture) {
  44048. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44049. return false;
  44050. }
  44051. }
  44052. }
  44053. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44054. // Bump texture cannot be not blocking.
  44055. if (!this._bumpTexture.isReady()) {
  44056. return false;
  44057. }
  44058. }
  44059. var refractionTexture = this._getRefractionTexture();
  44060. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44061. if (!refractionTexture.isReadyOrNotBlocking()) {
  44062. return false;
  44063. }
  44064. }
  44065. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44066. // This is blocking.
  44067. if (!this._environmentBRDFTexture.isReady()) {
  44068. return false;
  44069. }
  44070. }
  44071. }
  44072. }
  44073. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44074. if (!this._imageProcessingConfiguration.isReady()) {
  44075. return false;
  44076. }
  44077. }
  44078. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44079. mesh.createNormals(true);
  44080. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44081. }
  44082. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44083. if (effect) {
  44084. scene.resetCachedMaterial();
  44085. subMesh.setEffect(effect, defines);
  44086. this.buildUniformLayout();
  44087. }
  44088. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44089. return false;
  44090. }
  44091. defines._renderId = scene.getRenderId();
  44092. this._wasPreviouslyReady = true;
  44093. return true;
  44094. };
  44095. /**
  44096. * Specifies if the material uses metallic roughness workflow.
  44097. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44098. */
  44099. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44100. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44101. return true;
  44102. }
  44103. return false;
  44104. };
  44105. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44106. if (onCompiled === void 0) { onCompiled = null; }
  44107. if (onError === void 0) { onError = null; }
  44108. if (useInstances === void 0) { useInstances = null; }
  44109. if (useClipPlane === void 0) { useClipPlane = null; }
  44110. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44111. if (!defines.isDirty) {
  44112. return null;
  44113. }
  44114. defines.markAsProcessed();
  44115. var scene = this.getScene();
  44116. var engine = scene.getEngine();
  44117. // Fallbacks
  44118. var fallbacks = new BABYLON.EffectFallbacks();
  44119. var fallbackRank = 0;
  44120. if (defines.USESPHERICALINVERTEX) {
  44121. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44122. }
  44123. if (defines.FOG) {
  44124. fallbacks.addFallback(fallbackRank, "FOG");
  44125. }
  44126. if (defines.SPECULARAA) {
  44127. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44128. }
  44129. if (defines.POINTSIZE) {
  44130. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44131. }
  44132. if (defines.LOGARITHMICDEPTH) {
  44133. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44134. }
  44135. if (defines.PARALLAX) {
  44136. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44137. }
  44138. if (defines.PARALLAXOCCLUSION) {
  44139. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44140. }
  44141. if (defines.ENVIRONMENTBRDF) {
  44142. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44143. }
  44144. if (defines.TANGENT) {
  44145. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44146. }
  44147. if (defines.BUMP) {
  44148. fallbacks.addFallback(fallbackRank++, "BUMP");
  44149. }
  44150. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44151. if (defines.SPECULARTERM) {
  44152. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44153. }
  44154. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44155. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44156. }
  44157. if (defines.LIGHTMAP) {
  44158. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44159. }
  44160. if (defines.NORMAL) {
  44161. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44162. }
  44163. if (defines.AMBIENT) {
  44164. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44165. }
  44166. if (defines.EMISSIVE) {
  44167. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44168. }
  44169. if (defines.VERTEXCOLOR) {
  44170. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44171. }
  44172. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44173. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44174. }
  44175. if (defines.MORPHTARGETS) {
  44176. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44177. }
  44178. //Attributes
  44179. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44180. if (defines.NORMAL) {
  44181. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44182. }
  44183. if (defines.TANGENT) {
  44184. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44185. }
  44186. if (defines.UV1) {
  44187. attribs.push(BABYLON.VertexBuffer.UVKind);
  44188. }
  44189. if (defines.UV2) {
  44190. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44191. }
  44192. if (defines.VERTEXCOLOR) {
  44193. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44194. }
  44195. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44196. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44197. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44198. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44199. "vFogInfos", "vFogColor", "pointSize",
  44200. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44201. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44202. "mBones",
  44203. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44204. "vLightingIntensity",
  44205. "logarithmicDepthConstant",
  44206. "vSphericalX", "vSphericalY", "vSphericalZ",
  44207. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44208. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44209. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44210. "vTangentSpaceParams"
  44211. ];
  44212. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44213. "bumpSampler", "lightmapSampler", "opacitySampler",
  44214. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44215. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44216. "microSurfaceSampler", "environmentBrdfSampler"];
  44217. var uniformBuffers = ["Material", "Scene"];
  44218. if (BABYLON.ImageProcessingConfiguration) {
  44219. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44220. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44221. }
  44222. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44223. uniformsNames: uniforms,
  44224. uniformBuffersNames: uniformBuffers,
  44225. samplers: samplers,
  44226. defines: defines,
  44227. maxSimultaneousLights: this._maxSimultaneousLights
  44228. });
  44229. var join = defines.toString();
  44230. return engine.createEffect("pbr", {
  44231. attributes: attribs,
  44232. uniformsNames: uniforms,
  44233. uniformBuffersNames: uniformBuffers,
  44234. samplers: samplers,
  44235. defines: join,
  44236. fallbacks: fallbacks,
  44237. onCompiled: onCompiled,
  44238. onError: onError,
  44239. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44240. }, engine);
  44241. };
  44242. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44243. if (useInstances === void 0) { useInstances = null; }
  44244. if (useClipPlane === void 0) { useClipPlane = null; }
  44245. var scene = this.getScene();
  44246. var engine = scene.getEngine();
  44247. // Lights
  44248. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44249. defines._needNormals = true;
  44250. // Textures
  44251. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44252. if (defines._areTexturesDirty) {
  44253. defines._needUVs = false;
  44254. if (scene.texturesEnabled) {
  44255. if (scene.getEngine().getCaps().textureLOD) {
  44256. defines.LODBASEDMICROSFURACE = true;
  44257. }
  44258. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44259. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44260. }
  44261. else {
  44262. defines.ALBEDO = false;
  44263. }
  44264. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44265. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44266. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44267. }
  44268. else {
  44269. defines.AMBIENT = false;
  44270. }
  44271. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44272. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44273. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44274. }
  44275. else {
  44276. defines.OPACITY = false;
  44277. }
  44278. var reflectionTexture = this._getReflectionTexture();
  44279. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44280. defines.REFLECTION = true;
  44281. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44282. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44283. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44284. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44285. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44286. defines.INVERTCUBICMAP = true;
  44287. }
  44288. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44289. switch (reflectionTexture.coordinatesMode) {
  44290. case BABYLON.Texture.EXPLICIT_MODE:
  44291. defines.REFLECTIONMAP_EXPLICIT = true;
  44292. break;
  44293. case BABYLON.Texture.PLANAR_MODE:
  44294. defines.REFLECTIONMAP_PLANAR = true;
  44295. break;
  44296. case BABYLON.Texture.PROJECTION_MODE:
  44297. defines.REFLECTIONMAP_PROJECTION = true;
  44298. break;
  44299. case BABYLON.Texture.SKYBOX_MODE:
  44300. defines.REFLECTIONMAP_SKYBOX = true;
  44301. break;
  44302. case BABYLON.Texture.SPHERICAL_MODE:
  44303. defines.REFLECTIONMAP_SPHERICAL = true;
  44304. break;
  44305. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44306. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44307. break;
  44308. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44309. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44310. break;
  44311. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44312. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44313. break;
  44314. case BABYLON.Texture.CUBIC_MODE:
  44315. case BABYLON.Texture.INVCUBIC_MODE:
  44316. default:
  44317. defines.REFLECTIONMAP_CUBIC = true;
  44318. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44319. break;
  44320. }
  44321. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44322. if (reflectionTexture.sphericalPolynomial) {
  44323. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44324. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44325. defines.USESPHERICALINVERTEX = false;
  44326. }
  44327. else {
  44328. defines.USESPHERICALINVERTEX = true;
  44329. }
  44330. }
  44331. }
  44332. else {
  44333. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44334. }
  44335. }
  44336. else {
  44337. defines.REFLECTION = false;
  44338. defines.REFLECTIONMAP_3D = false;
  44339. defines.REFLECTIONMAP_SPHERICAL = false;
  44340. defines.REFLECTIONMAP_PLANAR = false;
  44341. defines.REFLECTIONMAP_CUBIC = false;
  44342. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44343. defines.REFLECTIONMAP_PROJECTION = false;
  44344. defines.REFLECTIONMAP_SKYBOX = false;
  44345. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44346. defines.REFLECTIONMAP_EXPLICIT = false;
  44347. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44348. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44349. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44350. defines.INVERTCUBICMAP = false;
  44351. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44352. defines.USESPHERICALINVERTEX = false;
  44353. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44354. defines.LODINREFLECTIONALPHA = false;
  44355. defines.GAMMAREFLECTION = false;
  44356. defines.RGBDREFLECTION = false;
  44357. }
  44358. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44359. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44360. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44361. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44362. }
  44363. else {
  44364. defines.LIGHTMAP = false;
  44365. }
  44366. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44367. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44368. }
  44369. else {
  44370. defines.EMISSIVE = false;
  44371. }
  44372. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44373. if (this._metallicTexture) {
  44374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44375. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44376. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44377. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44378. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44379. }
  44380. else if (this._reflectivityTexture) {
  44381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44382. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44383. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44384. }
  44385. else {
  44386. defines.REFLECTIVITY = false;
  44387. }
  44388. if (this._microSurfaceTexture) {
  44389. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44390. }
  44391. else {
  44392. defines.MICROSURFACEMAP = false;
  44393. }
  44394. }
  44395. else {
  44396. defines.REFLECTIVITY = false;
  44397. defines.MICROSURFACEMAP = false;
  44398. }
  44399. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44400. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44401. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44402. defines.PARALLAX = true;
  44403. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44404. }
  44405. else {
  44406. defines.PARALLAX = false;
  44407. }
  44408. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44409. }
  44410. else {
  44411. defines.BUMP = false;
  44412. }
  44413. var refractionTexture = this._getRefractionTexture();
  44414. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44415. defines.REFRACTION = true;
  44416. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44417. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44418. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44419. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44420. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44421. if (this._linkRefractionWithTransparency) {
  44422. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44423. }
  44424. }
  44425. else {
  44426. defines.REFRACTION = false;
  44427. }
  44428. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44429. defines.ENVIRONMENTBRDF = true;
  44430. }
  44431. else {
  44432. defines.ENVIRONMENTBRDF = false;
  44433. }
  44434. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44435. defines.ALPHAFROMALBEDO = true;
  44436. }
  44437. else {
  44438. defines.ALPHAFROMALBEDO = false;
  44439. }
  44440. }
  44441. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44442. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44443. defines.USEPHYSICALLIGHTFALLOFF = false;
  44444. defines.USEGLTFLIGHTFALLOFF = false;
  44445. }
  44446. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44447. defines.USEPHYSICALLIGHTFALLOFF = false;
  44448. defines.USEGLTFLIGHTFALLOFF = true;
  44449. }
  44450. else {
  44451. defines.USEPHYSICALLIGHTFALLOFF = true;
  44452. defines.USEGLTFLIGHTFALLOFF = false;
  44453. }
  44454. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44455. if (!this.backFaceCulling && this._twoSidedLighting) {
  44456. defines.TWOSIDEDLIGHTING = true;
  44457. }
  44458. else {
  44459. defines.TWOSIDEDLIGHTING = false;
  44460. }
  44461. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44462. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44463. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44464. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44465. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44466. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44467. }
  44468. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44469. this._imageProcessingConfiguration.prepareDefines(defines);
  44470. }
  44471. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44472. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44473. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44474. // Misc.
  44475. if (defines._areMiscDirty) {
  44476. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44477. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44478. }
  44479. // Values that need to be evaluated on every frame
  44480. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44481. // Attribs
  44482. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44483. };
  44484. /**
  44485. * Force shader compilation
  44486. */
  44487. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44488. var _this = this;
  44489. var localOptions = __assign({ clipPlane: false }, options);
  44490. var defines = new PBRMaterialDefines();
  44491. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44492. if (effect.isReady()) {
  44493. if (onCompiled) {
  44494. onCompiled(this);
  44495. }
  44496. }
  44497. else {
  44498. effect.onCompileObservable.add(function () {
  44499. if (onCompiled) {
  44500. onCompiled(_this);
  44501. }
  44502. });
  44503. }
  44504. };
  44505. /**
  44506. * Initializes the uniform buffer layout for the shader.
  44507. */
  44508. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44509. // Order is important !
  44510. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44511. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44512. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44513. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44514. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44515. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44516. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44517. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44518. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44519. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44520. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44521. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44522. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44523. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44524. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44525. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44526. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44527. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44528. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44529. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44530. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44531. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44532. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44533. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44534. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44535. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44536. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44537. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44538. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44539. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44540. this._uniformBuffer.addUniform("pointSize", 1);
  44541. this._uniformBuffer.create();
  44542. };
  44543. /**
  44544. * Unbinds the textures.
  44545. */
  44546. PBRBaseMaterial.prototype.unbind = function () {
  44547. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44548. this._uniformBuffer.setTexture("reflectionSampler", null);
  44549. }
  44550. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44551. this._uniformBuffer.setTexture("refractionSampler", null);
  44552. }
  44553. _super.prototype.unbind.call(this);
  44554. };
  44555. /**
  44556. * Binds the submesh data.
  44557. * @param world - The world matrix.
  44558. * @param mesh - The BJS mesh.
  44559. * @param subMesh - A submesh of the BJS mesh.
  44560. */
  44561. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44562. var scene = this.getScene();
  44563. var defines = subMesh._materialDefines;
  44564. if (!defines) {
  44565. return;
  44566. }
  44567. var effect = subMesh.effect;
  44568. if (!effect) {
  44569. return;
  44570. }
  44571. this._activeEffect = effect;
  44572. // Matrices
  44573. this.bindOnlyWorldMatrix(world);
  44574. // Normal Matrix
  44575. if (defines.OBJECTSPACE_NORMALMAP) {
  44576. world.toNormalMatrix(this._normalMatrix);
  44577. this.bindOnlyNormalMatrix(this._normalMatrix);
  44578. }
  44579. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44580. // Bones
  44581. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44582. var reflectionTexture = null;
  44583. if (mustRebind) {
  44584. this._uniformBuffer.bindToEffect(effect, "Material");
  44585. this.bindViewProjection(effect);
  44586. reflectionTexture = this._getReflectionTexture();
  44587. var refractionTexture = this._getRefractionTexture();
  44588. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44589. // Texture uniforms
  44590. if (scene.texturesEnabled) {
  44591. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44592. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44593. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44594. }
  44595. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44596. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44597. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44598. }
  44599. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44600. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44601. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44602. }
  44603. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44604. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44605. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44606. if (reflectionTexture.boundingBoxSize) {
  44607. var cubeTexture = reflectionTexture;
  44608. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44609. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44610. }
  44611. var polynomials = reflectionTexture.sphericalPolynomial;
  44612. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44613. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44614. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44615. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44616. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44617. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44618. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44619. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44620. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44621. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44622. }
  44623. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44624. }
  44625. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44626. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44627. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44628. }
  44629. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44630. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44631. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44632. }
  44633. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44634. if (this._metallicTexture) {
  44635. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44636. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44637. }
  44638. else if (this._reflectivityTexture) {
  44639. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44640. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44641. }
  44642. if (this._microSurfaceTexture) {
  44643. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44644. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44645. }
  44646. }
  44647. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44648. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44649. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44650. if (scene._mirroredCameraPosition) {
  44651. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44652. }
  44653. else {
  44654. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44655. }
  44656. }
  44657. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44658. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44659. var depth = 1.0;
  44660. if (!refractionTexture.isCube) {
  44661. if (refractionTexture.depth) {
  44662. depth = refractionTexture.depth;
  44663. }
  44664. }
  44665. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44666. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44667. }
  44668. }
  44669. // Point size
  44670. if (this.pointsCloud) {
  44671. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44672. }
  44673. // Colors
  44674. if (defines.METALLICWORKFLOW) {
  44675. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44676. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44677. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44678. }
  44679. else {
  44680. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44681. }
  44682. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44683. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44684. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44685. // Misc
  44686. this._lightingInfos.x = this._directIntensity;
  44687. this._lightingInfos.y = this._emissiveIntensity;
  44688. this._lightingInfos.z = this._environmentIntensity;
  44689. this._lightingInfos.w = this._specularIntensity;
  44690. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44691. }
  44692. // Textures
  44693. if (scene.texturesEnabled) {
  44694. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44695. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44696. }
  44697. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44698. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44699. }
  44700. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44701. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44702. }
  44703. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44704. if (defines.LODBASEDMICROSFURACE) {
  44705. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44706. }
  44707. else {
  44708. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44709. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44710. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44711. }
  44712. }
  44713. if (defines.ENVIRONMENTBRDF) {
  44714. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44715. }
  44716. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44717. if (defines.LODBASEDMICROSFURACE) {
  44718. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44719. }
  44720. else {
  44721. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44722. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44723. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44724. }
  44725. }
  44726. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44727. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44728. }
  44729. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44730. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44731. }
  44732. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44733. if (this._metallicTexture) {
  44734. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44735. }
  44736. else if (this._reflectivityTexture) {
  44737. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44738. }
  44739. if (this._microSurfaceTexture) {
  44740. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44741. }
  44742. }
  44743. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44744. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44745. }
  44746. }
  44747. // Clip plane
  44748. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44749. // Colors
  44750. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44751. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44752. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44753. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44754. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44755. }
  44756. if (mustRebind || !this.isFrozen) {
  44757. // Lights
  44758. if (scene.lightsEnabled && !this._disableLighting) {
  44759. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44760. }
  44761. // View
  44762. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44763. this.bindView(effect);
  44764. }
  44765. // Fog
  44766. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44767. // Morph targets
  44768. if (defines.NUM_MORPH_INFLUENCERS) {
  44769. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44770. }
  44771. // image processing
  44772. this._imageProcessingConfiguration.bind(this._activeEffect);
  44773. // Log. depth
  44774. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44775. }
  44776. this._uniformBuffer.update();
  44777. this._afterBind(mesh, this._activeEffect);
  44778. };
  44779. /**
  44780. * Returns the animatable textures.
  44781. * @returns - Array of animatable textures.
  44782. */
  44783. PBRBaseMaterial.prototype.getAnimatables = function () {
  44784. var results = [];
  44785. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44786. results.push(this._albedoTexture);
  44787. }
  44788. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44789. results.push(this._ambientTexture);
  44790. }
  44791. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44792. results.push(this._opacityTexture);
  44793. }
  44794. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44795. results.push(this._reflectionTexture);
  44796. }
  44797. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44798. results.push(this._emissiveTexture);
  44799. }
  44800. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44801. results.push(this._metallicTexture);
  44802. }
  44803. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44804. results.push(this._reflectivityTexture);
  44805. }
  44806. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44807. results.push(this._bumpTexture);
  44808. }
  44809. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44810. results.push(this._lightmapTexture);
  44811. }
  44812. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44813. results.push(this._refractionTexture);
  44814. }
  44815. return results;
  44816. };
  44817. /**
  44818. * Returns the texture used for reflections.
  44819. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44820. */
  44821. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44822. if (this._reflectionTexture) {
  44823. return this._reflectionTexture;
  44824. }
  44825. return this.getScene().environmentTexture;
  44826. };
  44827. /**
  44828. * Returns the texture used for refraction or null if none is used.
  44829. * @returns - Refection texture if present. If no refraction texture and refraction
  44830. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44831. */
  44832. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44833. if (this._refractionTexture) {
  44834. return this._refractionTexture;
  44835. }
  44836. if (this._linkRefractionWithTransparency) {
  44837. return this.getScene().environmentTexture;
  44838. }
  44839. return null;
  44840. };
  44841. /**
  44842. * Disposes the resources of the material.
  44843. * @param forceDisposeEffect - Forces the disposal of effects.
  44844. * @param forceDisposeTextures - Forces the disposal of all textures.
  44845. */
  44846. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44847. if (forceDisposeTextures) {
  44848. if (this._albedoTexture) {
  44849. this._albedoTexture.dispose();
  44850. }
  44851. if (this._ambientTexture) {
  44852. this._ambientTexture.dispose();
  44853. }
  44854. if (this._opacityTexture) {
  44855. this._opacityTexture.dispose();
  44856. }
  44857. if (this._reflectionTexture) {
  44858. this._reflectionTexture.dispose();
  44859. }
  44860. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44861. this._environmentBRDFTexture.dispose();
  44862. }
  44863. if (this._emissiveTexture) {
  44864. this._emissiveTexture.dispose();
  44865. }
  44866. if (this._metallicTexture) {
  44867. this._metallicTexture.dispose();
  44868. }
  44869. if (this._reflectivityTexture) {
  44870. this._reflectivityTexture.dispose();
  44871. }
  44872. if (this._bumpTexture) {
  44873. this._bumpTexture.dispose();
  44874. }
  44875. if (this._lightmapTexture) {
  44876. this._lightmapTexture.dispose();
  44877. }
  44878. if (this._refractionTexture) {
  44879. this._refractionTexture.dispose();
  44880. }
  44881. }
  44882. this._renderTargets.dispose();
  44883. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44884. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44885. }
  44886. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44887. };
  44888. /**
  44889. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44890. */
  44891. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44892. /**
  44893. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44894. * to enhance interoperability with other engines.
  44895. */
  44896. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44897. /**
  44898. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44899. * to enhance interoperability with other materials.
  44900. */
  44901. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44902. /**
  44903. * Stores the reflectivity values based on metallic roughness workflow.
  44904. */
  44905. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44906. __decorate([
  44907. BABYLON.serializeAsImageProcessingConfiguration()
  44908. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44909. __decorate([
  44910. BABYLON.serialize()
  44911. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44912. __decorate([
  44913. BABYLON.serialize()
  44914. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44915. return PBRBaseMaterial;
  44916. }(BABYLON.PushMaterial));
  44917. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44918. })(BABYLON || (BABYLON = {}));
  44919. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44920. var BABYLON;
  44921. (function (BABYLON) {
  44922. /**
  44923. * The Physically based simple base material of BJS.
  44924. *
  44925. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44926. * It is used as the base class for both the specGloss and metalRough conventions.
  44927. */
  44928. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44929. __extends(PBRBaseSimpleMaterial, _super);
  44930. /**
  44931. * Instantiates a new PBRMaterial instance.
  44932. *
  44933. * @param name The material name
  44934. * @param scene The scene the material will be use in.
  44935. */
  44936. function PBRBaseSimpleMaterial(name, scene) {
  44937. var _this = _super.call(this, name, scene) || this;
  44938. /**
  44939. * Number of Simultaneous lights allowed on the material.
  44940. */
  44941. _this.maxSimultaneousLights = 4;
  44942. /**
  44943. * If sets to true, disables all the lights affecting the material.
  44944. */
  44945. _this.disableLighting = false;
  44946. /**
  44947. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44948. */
  44949. _this.invertNormalMapX = false;
  44950. /**
  44951. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44952. */
  44953. _this.invertNormalMapY = false;
  44954. /**
  44955. * Emissivie color used to self-illuminate the model.
  44956. */
  44957. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44958. /**
  44959. * Occlusion Channel Strenght.
  44960. */
  44961. _this.occlusionStrength = 1.0;
  44962. _this.useLightmapAsShadowmap = false;
  44963. _this._useAlphaFromAlbedoTexture = true;
  44964. _this._useAmbientInGrayScale = true;
  44965. return _this;
  44966. }
  44967. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44968. /**
  44969. * Gets the current double sided mode.
  44970. */
  44971. get: function () {
  44972. return this._twoSidedLighting;
  44973. },
  44974. /**
  44975. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44976. */
  44977. set: function (value) {
  44978. if (this._twoSidedLighting === value) {
  44979. return;
  44980. }
  44981. this._twoSidedLighting = value;
  44982. this.backFaceCulling = !value;
  44983. this._markAllSubMeshesAsTexturesDirty();
  44984. },
  44985. enumerable: true,
  44986. configurable: true
  44987. });
  44988. /**
  44989. * Return the active textures of the material.
  44990. */
  44991. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44992. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44993. if (this.environmentTexture) {
  44994. activeTextures.push(this.environmentTexture);
  44995. }
  44996. if (this.normalTexture) {
  44997. activeTextures.push(this.normalTexture);
  44998. }
  44999. if (this.emissiveTexture) {
  45000. activeTextures.push(this.emissiveTexture);
  45001. }
  45002. if (this.occlusionTexture) {
  45003. activeTextures.push(this.occlusionTexture);
  45004. }
  45005. if (this.lightmapTexture) {
  45006. activeTextures.push(this.lightmapTexture);
  45007. }
  45008. return activeTextures;
  45009. };
  45010. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45011. if (_super.prototype.hasTexture.call(this, texture)) {
  45012. return true;
  45013. }
  45014. if (this.lightmapTexture === texture) {
  45015. return true;
  45016. }
  45017. return false;
  45018. };
  45019. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45020. return "PBRBaseSimpleMaterial";
  45021. };
  45022. __decorate([
  45023. BABYLON.serialize(),
  45024. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45025. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45026. __decorate([
  45027. BABYLON.serialize(),
  45028. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45029. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45030. __decorate([
  45031. BABYLON.serializeAsTexture(),
  45032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45033. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45034. __decorate([
  45035. BABYLON.serialize(),
  45036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45037. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45038. __decorate([
  45039. BABYLON.serialize(),
  45040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45041. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45042. __decorate([
  45043. BABYLON.serializeAsTexture(),
  45044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45045. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45046. __decorate([
  45047. BABYLON.serializeAsColor3("emissive"),
  45048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45049. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45050. __decorate([
  45051. BABYLON.serializeAsTexture(),
  45052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45053. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45054. __decorate([
  45055. BABYLON.serialize(),
  45056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45057. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45058. __decorate([
  45059. BABYLON.serializeAsTexture(),
  45060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45061. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45062. __decorate([
  45063. BABYLON.serialize(),
  45064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45065. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45066. __decorate([
  45067. BABYLON.serialize()
  45068. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45069. __decorate([
  45070. BABYLON.serializeAsTexture(),
  45071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45072. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45073. __decorate([
  45074. BABYLON.serialize(),
  45075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45076. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45077. return PBRBaseSimpleMaterial;
  45078. }(BABYLON.PBRBaseMaterial));
  45079. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45080. })(BABYLON || (BABYLON = {}));
  45081. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45082. var BABYLON;
  45083. (function (BABYLON) {
  45084. /**
  45085. * The Physically based material of BJS.
  45086. *
  45087. * This offers the main features of a standard PBR material.
  45088. * For more information, please refer to the documentation :
  45089. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45090. */
  45091. var PBRMaterial = /** @class */ (function (_super) {
  45092. __extends(PBRMaterial, _super);
  45093. /**
  45094. * Instantiates a new PBRMaterial instance.
  45095. *
  45096. * @param name The material name
  45097. * @param scene The scene the material will be use in.
  45098. */
  45099. function PBRMaterial(name, scene) {
  45100. var _this = _super.call(this, name, scene) || this;
  45101. /**
  45102. * Intensity of the direct lights e.g. the four lights available in your scene.
  45103. * This impacts both the direct diffuse and specular highlights.
  45104. */
  45105. _this.directIntensity = 1.0;
  45106. /**
  45107. * Intensity of the emissive part of the material.
  45108. * This helps controlling the emissive effect without modifying the emissive color.
  45109. */
  45110. _this.emissiveIntensity = 1.0;
  45111. /**
  45112. * Intensity of the environment e.g. how much the environment will light the object
  45113. * either through harmonics for rough material or through the refelction for shiny ones.
  45114. */
  45115. _this.environmentIntensity = 1.0;
  45116. /**
  45117. * This is a special control allowing the reduction of the specular highlights coming from the
  45118. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45119. */
  45120. _this.specularIntensity = 1.0;
  45121. /**
  45122. * Debug Control allowing disabling the bump map on this material.
  45123. */
  45124. _this.disableBumpMap = false;
  45125. /**
  45126. * AKA Occlusion Texture Intensity in other nomenclature.
  45127. */
  45128. _this.ambientTextureStrength = 1.0;
  45129. /**
  45130. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45131. * 1 means it completely occludes it
  45132. * 0 mean it has no impact
  45133. */
  45134. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45135. /**
  45136. * The color of a material in ambient lighting.
  45137. */
  45138. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45139. /**
  45140. * AKA Diffuse Color in other nomenclature.
  45141. */
  45142. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45143. /**
  45144. * AKA Specular Color in other nomenclature.
  45145. */
  45146. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45147. /**
  45148. * The color reflected from the material.
  45149. */
  45150. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45151. /**
  45152. * The color emitted from the material.
  45153. */
  45154. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45155. /**
  45156. * AKA Glossiness in other nomenclature.
  45157. */
  45158. _this.microSurface = 1.0;
  45159. /**
  45160. * source material index of refraction (IOR)' / 'destination material IOR.
  45161. */
  45162. _this.indexOfRefraction = 0.66;
  45163. /**
  45164. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45165. */
  45166. _this.invertRefractionY = false;
  45167. /**
  45168. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45169. * Materials half opaque for instance using refraction could benefit from this control.
  45170. */
  45171. _this.linkRefractionWithTransparency = false;
  45172. _this.useLightmapAsShadowmap = false;
  45173. /**
  45174. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45175. */
  45176. _this.useAlphaFromAlbedoTexture = false;
  45177. /**
  45178. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45179. */
  45180. _this.forceAlphaTest = false;
  45181. /**
  45182. * Defines the alpha limits in alpha test mode.
  45183. */
  45184. _this.alphaCutOff = 0.4;
  45185. /**
  45186. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45187. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45188. */
  45189. _this.useSpecularOverAlpha = true;
  45190. /**
  45191. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45192. */
  45193. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45194. /**
  45195. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45196. */
  45197. _this.useRoughnessFromMetallicTextureAlpha = true;
  45198. /**
  45199. * Specifies if the metallic texture contains the roughness information in its green channel.
  45200. */
  45201. _this.useRoughnessFromMetallicTextureGreen = false;
  45202. /**
  45203. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45204. */
  45205. _this.useMetallnessFromMetallicTextureBlue = false;
  45206. /**
  45207. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45208. */
  45209. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45210. /**
  45211. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45212. */
  45213. _this.useAmbientInGrayScale = false;
  45214. /**
  45215. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45216. * The material will try to infer what glossiness each pixel should be.
  45217. */
  45218. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45219. /**
  45220. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45221. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45222. */
  45223. _this.useRadianceOverAlpha = true;
  45224. /**
  45225. * Allows using an object space normal map (instead of tangent space).
  45226. */
  45227. _this.useObjectSpaceNormalMap = false;
  45228. /**
  45229. * Allows using the bump map in parallax mode.
  45230. */
  45231. _this.useParallax = false;
  45232. /**
  45233. * Allows using the bump map in parallax occlusion mode.
  45234. */
  45235. _this.useParallaxOcclusion = false;
  45236. /**
  45237. * Controls the scale bias of the parallax mode.
  45238. */
  45239. _this.parallaxScaleBias = 0.05;
  45240. /**
  45241. * If sets to true, disables all the lights affecting the material.
  45242. */
  45243. _this.disableLighting = false;
  45244. /**
  45245. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45246. */
  45247. _this.forceIrradianceInFragment = false;
  45248. /**
  45249. * Number of Simultaneous lights allowed on the material.
  45250. */
  45251. _this.maxSimultaneousLights = 4;
  45252. /**
  45253. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45254. */
  45255. _this.invertNormalMapX = false;
  45256. /**
  45257. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45258. */
  45259. _this.invertNormalMapY = false;
  45260. /**
  45261. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45262. */
  45263. _this.twoSidedLighting = false;
  45264. /**
  45265. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45266. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45267. */
  45268. _this.useAlphaFresnel = false;
  45269. /**
  45270. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45271. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45272. */
  45273. _this.useLinearAlphaFresnel = false;
  45274. /**
  45275. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45276. * And/Or occlude the blended part.
  45277. */
  45278. _this.environmentBRDFTexture = null;
  45279. /**
  45280. * Force normal to face away from face.
  45281. */
  45282. _this.forceNormalForward = false;
  45283. /**
  45284. * Enables specular anti aliasing in the PBR shader.
  45285. * It will both interacts on the Geometry for analytical and IBL lighting.
  45286. * It also prefilter the roughness map based on the bump values.
  45287. */
  45288. _this.enableSpecularAntiAliasing = false;
  45289. /**
  45290. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45291. * makes the reflect vector face the model (under horizon).
  45292. */
  45293. _this.useHorizonOcclusion = true;
  45294. /**
  45295. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45296. * too much the area relying on ambient texture to define their ambient occlusion.
  45297. */
  45298. _this.useRadianceOcclusion = true;
  45299. /**
  45300. * If set to true, no lighting calculations will be applied.
  45301. */
  45302. _this.unlit = false;
  45303. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45304. return _this;
  45305. }
  45306. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45307. /**
  45308. * BJS is using an harcoded light falloff based on a manually sets up range.
  45309. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45310. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45311. */
  45312. get: function () {
  45313. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45314. },
  45315. /**
  45316. * BJS is using an harcoded light falloff based on a manually sets up range.
  45317. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45318. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45319. */
  45320. set: function (value) {
  45321. if (value !== this.usePhysicalLightFalloff) {
  45322. // Ensure the effect will be rebuilt.
  45323. this._markAllSubMeshesAsTexturesDirty();
  45324. if (value) {
  45325. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45326. }
  45327. else {
  45328. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45329. }
  45330. }
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45336. /**
  45337. * In order to support the falloff compatibility with gltf, a special mode has been added
  45338. * to reproduce the gltf light falloff.
  45339. */
  45340. get: function () {
  45341. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45342. },
  45343. /**
  45344. * In order to support the falloff compatibility with gltf, a special mode has been added
  45345. * to reproduce the gltf light falloff.
  45346. */
  45347. set: function (value) {
  45348. if (value !== this.useGLTFLightFalloff) {
  45349. // Ensure the effect will be rebuilt.
  45350. this._markAllSubMeshesAsTexturesDirty();
  45351. if (value) {
  45352. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45353. }
  45354. else {
  45355. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45356. }
  45357. }
  45358. },
  45359. enumerable: true,
  45360. configurable: true
  45361. });
  45362. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45363. /**
  45364. * Gets the image processing configuration used either in this material.
  45365. */
  45366. get: function () {
  45367. return this._imageProcessingConfiguration;
  45368. },
  45369. /**
  45370. * Sets the Default image processing configuration used either in the this material.
  45371. *
  45372. * If sets to null, the scene one is in use.
  45373. */
  45374. set: function (value) {
  45375. this._attachImageProcessingConfiguration(value);
  45376. // Ensure the effect will be rebuilt.
  45377. this._markAllSubMeshesAsTexturesDirty();
  45378. },
  45379. enumerable: true,
  45380. configurable: true
  45381. });
  45382. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45383. /**
  45384. * Gets wether the color curves effect is enabled.
  45385. */
  45386. get: function () {
  45387. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45388. },
  45389. /**
  45390. * Sets wether the color curves effect is enabled.
  45391. */
  45392. set: function (value) {
  45393. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45399. /**
  45400. * Gets wether the color grading effect is enabled.
  45401. */
  45402. get: function () {
  45403. return this.imageProcessingConfiguration.colorGradingEnabled;
  45404. },
  45405. /**
  45406. * Gets wether the color grading effect is enabled.
  45407. */
  45408. set: function (value) {
  45409. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45410. },
  45411. enumerable: true,
  45412. configurable: true
  45413. });
  45414. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45415. /**
  45416. * Gets wether tonemapping is enabled or not.
  45417. */
  45418. get: function () {
  45419. return this._imageProcessingConfiguration.toneMappingEnabled;
  45420. },
  45421. /**
  45422. * Sets wether tonemapping is enabled or not
  45423. */
  45424. set: function (value) {
  45425. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. ;
  45431. ;
  45432. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45433. /**
  45434. * The camera exposure used on this material.
  45435. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45436. * This corresponds to a photographic exposure.
  45437. */
  45438. get: function () {
  45439. return this._imageProcessingConfiguration.exposure;
  45440. },
  45441. /**
  45442. * The camera exposure used on this material.
  45443. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45444. * This corresponds to a photographic exposure.
  45445. */
  45446. set: function (value) {
  45447. this._imageProcessingConfiguration.exposure = value;
  45448. },
  45449. enumerable: true,
  45450. configurable: true
  45451. });
  45452. ;
  45453. ;
  45454. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45455. /**
  45456. * Gets The camera contrast used on this material.
  45457. */
  45458. get: function () {
  45459. return this._imageProcessingConfiguration.contrast;
  45460. },
  45461. /**
  45462. * Sets The camera contrast used on this material.
  45463. */
  45464. set: function (value) {
  45465. this._imageProcessingConfiguration.contrast = value;
  45466. },
  45467. enumerable: true,
  45468. configurable: true
  45469. });
  45470. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45471. /**
  45472. * Gets the Color Grading 2D Lookup Texture.
  45473. */
  45474. get: function () {
  45475. return this._imageProcessingConfiguration.colorGradingTexture;
  45476. },
  45477. /**
  45478. * Sets the Color Grading 2D Lookup Texture.
  45479. */
  45480. set: function (value) {
  45481. this._imageProcessingConfiguration.colorGradingTexture = value;
  45482. },
  45483. enumerable: true,
  45484. configurable: true
  45485. });
  45486. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45487. /**
  45488. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45489. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45490. * 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;
  45491. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45492. */
  45493. get: function () {
  45494. return this._imageProcessingConfiguration.colorCurves;
  45495. },
  45496. /**
  45497. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45498. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45499. * 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;
  45500. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45501. */
  45502. set: function (value) {
  45503. this._imageProcessingConfiguration.colorCurves = value;
  45504. },
  45505. enumerable: true,
  45506. configurable: true
  45507. });
  45508. /**
  45509. * Returns the name of this material class.
  45510. */
  45511. PBRMaterial.prototype.getClassName = function () {
  45512. return "PBRMaterial";
  45513. };
  45514. /**
  45515. * Returns an array of the actively used textures.
  45516. * @returns - Array of BaseTextures
  45517. */
  45518. PBRMaterial.prototype.getActiveTextures = function () {
  45519. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45520. if (this._albedoTexture) {
  45521. activeTextures.push(this._albedoTexture);
  45522. }
  45523. if (this._ambientTexture) {
  45524. activeTextures.push(this._ambientTexture);
  45525. }
  45526. if (this._opacityTexture) {
  45527. activeTextures.push(this._opacityTexture);
  45528. }
  45529. if (this._reflectionTexture) {
  45530. activeTextures.push(this._reflectionTexture);
  45531. }
  45532. if (this._emissiveTexture) {
  45533. activeTextures.push(this._emissiveTexture);
  45534. }
  45535. if (this._reflectivityTexture) {
  45536. activeTextures.push(this._reflectivityTexture);
  45537. }
  45538. if (this._metallicTexture) {
  45539. activeTextures.push(this._metallicTexture);
  45540. }
  45541. if (this._microSurfaceTexture) {
  45542. activeTextures.push(this._microSurfaceTexture);
  45543. }
  45544. if (this._bumpTexture) {
  45545. activeTextures.push(this._bumpTexture);
  45546. }
  45547. if (this._lightmapTexture) {
  45548. activeTextures.push(this._lightmapTexture);
  45549. }
  45550. if (this._refractionTexture) {
  45551. activeTextures.push(this._refractionTexture);
  45552. }
  45553. return activeTextures;
  45554. };
  45555. /**
  45556. * Checks to see if a texture is used in the material.
  45557. * @param texture - Base texture to use.
  45558. * @returns - Boolean specifying if a texture is used in the material.
  45559. */
  45560. PBRMaterial.prototype.hasTexture = function (texture) {
  45561. if (_super.prototype.hasTexture.call(this, texture)) {
  45562. return true;
  45563. }
  45564. if (this._albedoTexture === texture) {
  45565. return true;
  45566. }
  45567. if (this._ambientTexture === texture) {
  45568. return true;
  45569. }
  45570. if (this._opacityTexture === texture) {
  45571. return true;
  45572. }
  45573. if (this._reflectionTexture === texture) {
  45574. return true;
  45575. }
  45576. if (this._reflectivityTexture === texture) {
  45577. return true;
  45578. }
  45579. if (this._metallicTexture === texture) {
  45580. return true;
  45581. }
  45582. if (this._microSurfaceTexture === texture) {
  45583. return true;
  45584. }
  45585. if (this._bumpTexture === texture) {
  45586. return true;
  45587. }
  45588. if (this._lightmapTexture === texture) {
  45589. return true;
  45590. }
  45591. if (this._refractionTexture === texture) {
  45592. return true;
  45593. }
  45594. return false;
  45595. };
  45596. /**
  45597. * Makes a duplicate of the current material.
  45598. * @param name - name to use for the new material.
  45599. */
  45600. PBRMaterial.prototype.clone = function (name) {
  45601. var _this = this;
  45602. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45603. clone.id = name;
  45604. clone.name = name;
  45605. return clone;
  45606. };
  45607. /**
  45608. * Serializes this PBR Material.
  45609. * @returns - An object with the serialized material.
  45610. */
  45611. PBRMaterial.prototype.serialize = function () {
  45612. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45613. serializationObject.customType = "BABYLON.PBRMaterial";
  45614. return serializationObject;
  45615. };
  45616. // Statics
  45617. /**
  45618. * Parses a PBR Material from a serialized object.
  45619. * @param source - Serialized object.
  45620. * @param scene - BJS scene instance.
  45621. * @param rootUrl - url for the scene object
  45622. * @returns - PBRMaterial
  45623. */
  45624. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45625. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45626. };
  45627. /**
  45628. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45629. */
  45630. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45631. /**
  45632. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45633. */
  45634. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45635. /**
  45636. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45637. */
  45638. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45639. /**
  45640. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45641. * They are also discarded below the alpha cutoff threshold to improve performances.
  45642. */
  45643. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45644. /**
  45645. * Defines the default value of how much AO map is occluding the analytical lights
  45646. * (point spot...).
  45647. */
  45648. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45649. __decorate([
  45650. BABYLON.serialize(),
  45651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45652. ], PBRMaterial.prototype, "directIntensity", void 0);
  45653. __decorate([
  45654. BABYLON.serialize(),
  45655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45656. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45657. __decorate([
  45658. BABYLON.serialize(),
  45659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45660. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45661. __decorate([
  45662. BABYLON.serialize(),
  45663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45664. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45665. __decorate([
  45666. BABYLON.serialize(),
  45667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45668. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45669. __decorate([
  45670. BABYLON.serializeAsTexture(),
  45671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45672. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45673. __decorate([
  45674. BABYLON.serializeAsTexture(),
  45675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45676. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45677. __decorate([
  45678. BABYLON.serialize(),
  45679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45680. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45681. __decorate([
  45682. BABYLON.serialize(),
  45683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45684. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45685. __decorate([
  45686. BABYLON.serializeAsTexture(),
  45687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45688. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45689. __decorate([
  45690. BABYLON.serializeAsTexture(),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45692. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45693. __decorate([
  45694. BABYLON.serializeAsTexture(),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45696. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45697. __decorate([
  45698. BABYLON.serializeAsTexture(),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45700. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45701. __decorate([
  45702. BABYLON.serializeAsTexture(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45704. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45705. __decorate([
  45706. BABYLON.serialize(),
  45707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45708. ], PBRMaterial.prototype, "metallic", void 0);
  45709. __decorate([
  45710. BABYLON.serialize(),
  45711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45712. ], PBRMaterial.prototype, "roughness", void 0);
  45713. __decorate([
  45714. BABYLON.serializeAsTexture(),
  45715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45716. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45717. __decorate([
  45718. BABYLON.serializeAsTexture(),
  45719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45720. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45721. __decorate([
  45722. BABYLON.serializeAsTexture(),
  45723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45724. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45725. __decorate([
  45726. BABYLON.serializeAsTexture(),
  45727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45728. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45729. __decorate([
  45730. BABYLON.serializeAsColor3("ambient"),
  45731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45732. ], PBRMaterial.prototype, "ambientColor", void 0);
  45733. __decorate([
  45734. BABYLON.serializeAsColor3("albedo"),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45736. ], PBRMaterial.prototype, "albedoColor", void 0);
  45737. __decorate([
  45738. BABYLON.serializeAsColor3("reflectivity"),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45740. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45741. __decorate([
  45742. BABYLON.serializeAsColor3("reflection"),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45744. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45745. __decorate([
  45746. BABYLON.serializeAsColor3("emissive"),
  45747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45748. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45749. __decorate([
  45750. BABYLON.serialize(),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45752. ], PBRMaterial.prototype, "microSurface", void 0);
  45753. __decorate([
  45754. BABYLON.serialize(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45756. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45757. __decorate([
  45758. BABYLON.serialize(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45760. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45764. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45769. __decorate([
  45770. BABYLON.serialize(),
  45771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45772. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45773. __decorate([
  45774. BABYLON.serialize(),
  45775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45776. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45777. __decorate([
  45778. BABYLON.serialize(),
  45779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45780. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45781. __decorate([
  45782. BABYLON.serialize(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45784. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45785. __decorate([
  45786. BABYLON.serialize(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45788. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45797. __decorate([
  45798. BABYLON.serialize(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45800. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45801. __decorate([
  45802. BABYLON.serialize(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45804. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45805. __decorate([
  45806. BABYLON.serialize(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45808. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45809. __decorate([
  45810. BABYLON.serialize(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45812. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45813. __decorate([
  45814. BABYLON.serialize()
  45815. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45816. __decorate([
  45817. BABYLON.serialize()
  45818. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45819. __decorate([
  45820. BABYLON.serialize(),
  45821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45822. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45823. __decorate([
  45824. BABYLON.serialize(),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45826. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45827. __decorate([
  45828. BABYLON.serialize(),
  45829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45830. ], PBRMaterial.prototype, "useParallax", void 0);
  45831. __decorate([
  45832. BABYLON.serialize(),
  45833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45834. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45835. __decorate([
  45836. BABYLON.serialize(),
  45837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45838. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45839. __decorate([
  45840. BABYLON.serialize(),
  45841. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45842. ], PBRMaterial.prototype, "disableLighting", void 0);
  45843. __decorate([
  45844. BABYLON.serialize(),
  45845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45846. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45847. __decorate([
  45848. BABYLON.serialize(),
  45849. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45850. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45851. __decorate([
  45852. BABYLON.serialize(),
  45853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45854. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45855. __decorate([
  45856. BABYLON.serialize(),
  45857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45858. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45859. __decorate([
  45860. BABYLON.serialize(),
  45861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45862. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45863. __decorate([
  45864. BABYLON.serialize(),
  45865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45866. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45867. __decorate([
  45868. BABYLON.serialize(),
  45869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45870. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45871. __decorate([
  45872. BABYLON.serializeAsTexture(),
  45873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45874. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45875. __decorate([
  45876. BABYLON.serialize(),
  45877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45878. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45879. __decorate([
  45880. BABYLON.serialize(),
  45881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45882. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45883. __decorate([
  45884. BABYLON.serialize(),
  45885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45886. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45887. __decorate([
  45888. BABYLON.serialize(),
  45889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45890. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45891. __decorate([
  45892. BABYLON.serialize(),
  45893. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45894. ], PBRMaterial.prototype, "unlit", void 0);
  45895. return PBRMaterial;
  45896. }(BABYLON.PBRBaseMaterial));
  45897. BABYLON.PBRMaterial = PBRMaterial;
  45898. })(BABYLON || (BABYLON = {}));
  45899. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45900. var BABYLON;
  45901. (function (BABYLON) {
  45902. /**
  45903. * The PBR material of BJS following the metal roughness convention.
  45904. *
  45905. * This fits to the PBR convention in the GLTF definition:
  45906. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45907. */
  45908. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45909. __extends(PBRMetallicRoughnessMaterial, _super);
  45910. /**
  45911. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45912. *
  45913. * @param name The material name
  45914. * @param scene The scene the material will be use in.
  45915. */
  45916. function PBRMetallicRoughnessMaterial(name, scene) {
  45917. var _this = _super.call(this, name, scene) || this;
  45918. _this._useRoughnessFromMetallicTextureAlpha = false;
  45919. _this._useRoughnessFromMetallicTextureGreen = true;
  45920. _this._useMetallnessFromMetallicTextureBlue = true;
  45921. _this.metallic = 1.0;
  45922. _this.roughness = 1.0;
  45923. return _this;
  45924. }
  45925. /**
  45926. * Return the currrent class name of the material.
  45927. */
  45928. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45929. return "PBRMetallicRoughnessMaterial";
  45930. };
  45931. /**
  45932. * Return the active textures of the material.
  45933. */
  45934. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45935. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45936. if (this.baseTexture) {
  45937. activeTextures.push(this.baseTexture);
  45938. }
  45939. if (this.metallicRoughnessTexture) {
  45940. activeTextures.push(this.metallicRoughnessTexture);
  45941. }
  45942. return activeTextures;
  45943. };
  45944. /**
  45945. * Checks to see if a texture is used in the material.
  45946. * @param texture - Base texture to use.
  45947. * @returns - Boolean specifying if a texture is used in the material.
  45948. */
  45949. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45950. if (_super.prototype.hasTexture.call(this, texture)) {
  45951. return true;
  45952. }
  45953. if (this.baseTexture === texture) {
  45954. return true;
  45955. }
  45956. if (this.metallicRoughnessTexture === texture) {
  45957. return true;
  45958. }
  45959. return false;
  45960. };
  45961. /**
  45962. * Makes a duplicate of the current material.
  45963. * @param name - name to use for the new material.
  45964. */
  45965. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45966. var _this = this;
  45967. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45968. clone.id = name;
  45969. clone.name = name;
  45970. return clone;
  45971. };
  45972. /**
  45973. * Serialize the material to a parsable JSON object.
  45974. */
  45975. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45977. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45978. return serializationObject;
  45979. };
  45980. /**
  45981. * Parses a JSON object correponding to the serialize function.
  45982. */
  45983. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45984. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45985. };
  45986. __decorate([
  45987. BABYLON.serializeAsColor3(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45989. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45990. __decorate([
  45991. BABYLON.serializeAsTexture(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45993. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45994. __decorate([
  45995. BABYLON.serialize(),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45997. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45998. __decorate([
  45999. BABYLON.serialize(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46001. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46002. __decorate([
  46003. BABYLON.serializeAsTexture(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46005. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46006. return PBRMetallicRoughnessMaterial;
  46007. }(BABYLON.PBRBaseSimpleMaterial));
  46008. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46009. })(BABYLON || (BABYLON = {}));
  46010. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46011. var BABYLON;
  46012. (function (BABYLON) {
  46013. /**
  46014. * The PBR material of BJS following the specular glossiness convention.
  46015. *
  46016. * This fits to the PBR convention in the GLTF definition:
  46017. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46018. */
  46019. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46020. __extends(PBRSpecularGlossinessMaterial, _super);
  46021. /**
  46022. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46023. *
  46024. * @param name The material name
  46025. * @param scene The scene the material will be use in.
  46026. */
  46027. function PBRSpecularGlossinessMaterial(name, scene) {
  46028. var _this = _super.call(this, name, scene) || this;
  46029. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46030. return _this;
  46031. }
  46032. /**
  46033. * Return the currrent class name of the material.
  46034. */
  46035. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46036. return "PBRSpecularGlossinessMaterial";
  46037. };
  46038. /**
  46039. * Return the active textures of the material.
  46040. */
  46041. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46042. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46043. if (this.diffuseTexture) {
  46044. activeTextures.push(this.diffuseTexture);
  46045. }
  46046. if (this.specularGlossinessTexture) {
  46047. activeTextures.push(this.specularGlossinessTexture);
  46048. }
  46049. return activeTextures;
  46050. };
  46051. /**
  46052. * Checks to see if a texture is used in the material.
  46053. * @param texture - Base texture to use.
  46054. * @returns - Boolean specifying if a texture is used in the material.
  46055. */
  46056. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46057. if (_super.prototype.hasTexture.call(this, texture)) {
  46058. return true;
  46059. }
  46060. if (this.diffuseTexture === texture) {
  46061. return true;
  46062. }
  46063. if (this.specularGlossinessTexture === texture) {
  46064. return true;
  46065. }
  46066. return false;
  46067. };
  46068. /**
  46069. * Makes a duplicate of the current material.
  46070. * @param name - name to use for the new material.
  46071. */
  46072. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46073. var _this = this;
  46074. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46075. clone.id = name;
  46076. clone.name = name;
  46077. return clone;
  46078. };
  46079. /**
  46080. * Serialize the material to a parsable JSON object.
  46081. */
  46082. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46083. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46084. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46085. return serializationObject;
  46086. };
  46087. /**
  46088. * Parses a JSON object correponding to the serialize function.
  46089. */
  46090. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46091. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46092. };
  46093. __decorate([
  46094. BABYLON.serializeAsColor3("diffuse"),
  46095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46096. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46097. __decorate([
  46098. BABYLON.serializeAsTexture(),
  46099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46100. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46101. __decorate([
  46102. BABYLON.serializeAsColor3("specular"),
  46103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46104. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46105. __decorate([
  46106. BABYLON.serialize(),
  46107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46108. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46109. __decorate([
  46110. BABYLON.serializeAsTexture(),
  46111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46112. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46113. return PBRSpecularGlossinessMaterial;
  46114. }(BABYLON.PBRBaseSimpleMaterial));
  46115. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46116. })(BABYLON || (BABYLON = {}));
  46117. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46118. var BABYLON;
  46119. (function (BABYLON) {
  46120. BABYLON.CameraInputTypes = {};
  46121. var CameraInputsManager = /** @class */ (function () {
  46122. function CameraInputsManager(camera) {
  46123. this.attached = {};
  46124. this.camera = camera;
  46125. this.checkInputs = function () { };
  46126. }
  46127. /**
  46128. * Add an input method to a camera
  46129. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46130. * @param input camera input method
  46131. */
  46132. CameraInputsManager.prototype.add = function (input) {
  46133. var type = input.getSimpleName();
  46134. if (this.attached[type]) {
  46135. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46136. return;
  46137. }
  46138. this.attached[type] = input;
  46139. input.camera = this.camera;
  46140. //for checkInputs, we are dynamically creating a function
  46141. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46142. if (input.checkInputs) {
  46143. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46144. }
  46145. if (this.attachedElement) {
  46146. input.attachControl(this.attachedElement);
  46147. }
  46148. };
  46149. /**
  46150. * Remove a specific input method from a camera
  46151. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46152. * @param inputToRemove camera input method
  46153. */
  46154. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46155. for (var cam in this.attached) {
  46156. var input = this.attached[cam];
  46157. if (input === inputToRemove) {
  46158. input.detachControl(this.attachedElement);
  46159. input.camera = null;
  46160. delete this.attached[cam];
  46161. this.rebuildInputCheck();
  46162. }
  46163. }
  46164. };
  46165. CameraInputsManager.prototype.removeByType = function (inputType) {
  46166. for (var cam in this.attached) {
  46167. var input = this.attached[cam];
  46168. if (input.getClassName() === inputType) {
  46169. input.detachControl(this.attachedElement);
  46170. input.camera = null;
  46171. delete this.attached[cam];
  46172. this.rebuildInputCheck();
  46173. }
  46174. }
  46175. };
  46176. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46177. var current = this.checkInputs;
  46178. return function () {
  46179. current();
  46180. fn();
  46181. };
  46182. };
  46183. CameraInputsManager.prototype.attachInput = function (input) {
  46184. if (this.attachedElement) {
  46185. input.attachControl(this.attachedElement, this.noPreventDefault);
  46186. }
  46187. };
  46188. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46189. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46190. if (this.attachedElement) {
  46191. return;
  46192. }
  46193. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46194. this.attachedElement = element;
  46195. this.noPreventDefault = noPreventDefault;
  46196. for (var cam in this.attached) {
  46197. this.attached[cam].attachControl(element, noPreventDefault);
  46198. }
  46199. };
  46200. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46201. if (disconnect === void 0) { disconnect = false; }
  46202. if (this.attachedElement !== element) {
  46203. return;
  46204. }
  46205. for (var cam in this.attached) {
  46206. this.attached[cam].detachControl(element);
  46207. if (disconnect) {
  46208. this.attached[cam].camera = null;
  46209. }
  46210. }
  46211. this.attachedElement = null;
  46212. };
  46213. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46214. this.checkInputs = function () { };
  46215. for (var cam in this.attached) {
  46216. var input = this.attached[cam];
  46217. if (input.checkInputs) {
  46218. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46219. }
  46220. }
  46221. };
  46222. /**
  46223. * Remove all attached input methods from a camera
  46224. */
  46225. CameraInputsManager.prototype.clear = function () {
  46226. if (this.attachedElement) {
  46227. this.detachElement(this.attachedElement, true);
  46228. }
  46229. this.attached = {};
  46230. this.attachedElement = null;
  46231. this.checkInputs = function () { };
  46232. };
  46233. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46234. var inputs = {};
  46235. for (var cam in this.attached) {
  46236. var input = this.attached[cam];
  46237. var res = BABYLON.SerializationHelper.Serialize(input);
  46238. inputs[input.getClassName()] = res;
  46239. }
  46240. serializedCamera.inputsmgr = inputs;
  46241. };
  46242. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46243. var parsedInputs = parsedCamera.inputsmgr;
  46244. if (parsedInputs) {
  46245. this.clear();
  46246. for (var n in parsedInputs) {
  46247. var construct = BABYLON.CameraInputTypes[n];
  46248. if (construct) {
  46249. var parsedinput = parsedInputs[n];
  46250. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46251. this.add(input);
  46252. }
  46253. }
  46254. }
  46255. else {
  46256. //2016-03-08 this part is for managing backward compatibility
  46257. for (var n in this.attached) {
  46258. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46259. if (construct) {
  46260. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46261. this.remove(this.attached[n]);
  46262. this.add(input);
  46263. }
  46264. }
  46265. }
  46266. };
  46267. return CameraInputsManager;
  46268. }());
  46269. BABYLON.CameraInputsManager = CameraInputsManager;
  46270. })(BABYLON || (BABYLON = {}));
  46271. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46272. var BABYLON;
  46273. (function (BABYLON) {
  46274. var TargetCamera = /** @class */ (function (_super) {
  46275. __extends(TargetCamera, _super);
  46276. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46277. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46278. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46279. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46280. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46281. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46282. _this.speed = 2.0;
  46283. _this.noRotationConstraint = false;
  46284. _this.lockedTarget = null;
  46285. /** @hidden */
  46286. _this._currentTarget = BABYLON.Vector3.Zero();
  46287. /** @hidden */
  46288. _this._viewMatrix = BABYLON.Matrix.Zero();
  46289. /** @hidden */
  46290. _this._camMatrix = BABYLON.Matrix.Zero();
  46291. /** @hidden */
  46292. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46293. /** @hidden */
  46294. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46295. /** @hidden */
  46296. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46297. /** @hidden */
  46298. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46299. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46300. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46301. _this._defaultUp = BABYLON.Vector3.Up();
  46302. _this._cachedRotationZ = 0;
  46303. return _this;
  46304. }
  46305. TargetCamera.prototype.getFrontPosition = function (distance) {
  46306. this.getWorldMatrix();
  46307. var direction = this.getTarget().subtract(this.position);
  46308. direction.normalize();
  46309. direction.scaleInPlace(distance);
  46310. return this.globalPosition.add(direction);
  46311. };
  46312. /** @hidden */
  46313. TargetCamera.prototype._getLockedTargetPosition = function () {
  46314. if (!this.lockedTarget) {
  46315. return null;
  46316. }
  46317. if (this.lockedTarget.absolutePosition) {
  46318. this.lockedTarget.computeWorldMatrix();
  46319. }
  46320. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46321. };
  46322. TargetCamera.prototype.storeState = function () {
  46323. this._storedPosition = this.position.clone();
  46324. this._storedRotation = this.rotation.clone();
  46325. if (this.rotationQuaternion) {
  46326. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46327. }
  46328. return _super.prototype.storeState.call(this);
  46329. };
  46330. /**
  46331. * Restored camera state. You must call storeState() first
  46332. * @returns whether it was successful or not
  46333. * @hidden
  46334. */
  46335. TargetCamera.prototype._restoreStateValues = function () {
  46336. if (!_super.prototype._restoreStateValues.call(this)) {
  46337. return false;
  46338. }
  46339. this.position = this._storedPosition.clone();
  46340. this.rotation = this._storedRotation.clone();
  46341. if (this.rotationQuaternion) {
  46342. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46343. }
  46344. this.cameraDirection.copyFromFloats(0, 0, 0);
  46345. this.cameraRotation.copyFromFloats(0, 0);
  46346. return true;
  46347. };
  46348. // Cache
  46349. /** @hidden */
  46350. TargetCamera.prototype._initCache = function () {
  46351. _super.prototype._initCache.call(this);
  46352. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46353. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46354. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46355. };
  46356. /** @hidden */
  46357. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46358. if (!ignoreParentClass) {
  46359. _super.prototype._updateCache.call(this);
  46360. }
  46361. var lockedTargetPosition = this._getLockedTargetPosition();
  46362. if (!lockedTargetPosition) {
  46363. this._cache.lockedTarget = null;
  46364. }
  46365. else {
  46366. if (!this._cache.lockedTarget) {
  46367. this._cache.lockedTarget = lockedTargetPosition.clone();
  46368. }
  46369. else {
  46370. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46371. }
  46372. }
  46373. this._cache.rotation.copyFrom(this.rotation);
  46374. if (this.rotationQuaternion)
  46375. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46376. };
  46377. // Synchronized
  46378. /** @hidden */
  46379. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46380. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46381. return false;
  46382. }
  46383. var lockedTargetPosition = this._getLockedTargetPosition();
  46384. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46385. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46386. };
  46387. // Methods
  46388. /** @hidden */
  46389. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46390. var engine = this.getEngine();
  46391. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46392. };
  46393. // Target
  46394. /** @hidden */
  46395. TargetCamera.prototype.setTarget = function (target) {
  46396. this.upVector.normalize();
  46397. if (this.position.z === target.z) {
  46398. this.position.z += BABYLON.Epsilon;
  46399. }
  46400. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46401. this._camMatrix.invert();
  46402. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46403. var vDir = target.subtract(this.position);
  46404. if (vDir.x >= 0.0) {
  46405. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46406. }
  46407. else {
  46408. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46409. }
  46410. this.rotation.z = 0;
  46411. if (isNaN(this.rotation.x)) {
  46412. this.rotation.x = 0;
  46413. }
  46414. if (isNaN(this.rotation.y)) {
  46415. this.rotation.y = 0;
  46416. }
  46417. if (isNaN(this.rotation.z)) {
  46418. this.rotation.z = 0;
  46419. }
  46420. if (this.rotationQuaternion) {
  46421. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46422. }
  46423. };
  46424. /**
  46425. * Return the current target position of the camera. This value is expressed in local space.
  46426. */
  46427. TargetCamera.prototype.getTarget = function () {
  46428. return this._currentTarget;
  46429. };
  46430. /** @hidden */
  46431. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46432. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46433. };
  46434. /** @hidden */
  46435. TargetCamera.prototype._updatePosition = function () {
  46436. if (this.parent) {
  46437. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46438. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46439. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46440. return;
  46441. }
  46442. this.position.addInPlace(this.cameraDirection);
  46443. };
  46444. /** @hidden */
  46445. TargetCamera.prototype._checkInputs = function () {
  46446. var needToMove = this._decideIfNeedsToMove();
  46447. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46448. // Move
  46449. if (needToMove) {
  46450. this._updatePosition();
  46451. }
  46452. // Rotate
  46453. if (needToRotate) {
  46454. this.rotation.x += this.cameraRotation.x;
  46455. this.rotation.y += this.cameraRotation.y;
  46456. //rotate, if quaternion is set and rotation was used
  46457. if (this.rotationQuaternion) {
  46458. var len = this.rotation.lengthSquared();
  46459. if (len) {
  46460. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46461. }
  46462. }
  46463. if (!this.noRotationConstraint) {
  46464. var limit = (Math.PI / 2) * 0.95;
  46465. if (this.rotation.x > limit)
  46466. this.rotation.x = limit;
  46467. if (this.rotation.x < -limit)
  46468. this.rotation.x = -limit;
  46469. }
  46470. }
  46471. // Inertia
  46472. if (needToMove) {
  46473. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46474. this.cameraDirection.x = 0;
  46475. }
  46476. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46477. this.cameraDirection.y = 0;
  46478. }
  46479. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46480. this.cameraDirection.z = 0;
  46481. }
  46482. this.cameraDirection.scaleInPlace(this.inertia);
  46483. }
  46484. if (needToRotate) {
  46485. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46486. this.cameraRotation.x = 0;
  46487. }
  46488. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46489. this.cameraRotation.y = 0;
  46490. }
  46491. this.cameraRotation.scaleInPlace(this.inertia);
  46492. }
  46493. _super.prototype._checkInputs.call(this);
  46494. };
  46495. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46496. if (this.rotationQuaternion) {
  46497. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46498. }
  46499. else {
  46500. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46501. }
  46502. };
  46503. /**
  46504. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46505. * @returns the current camera
  46506. */
  46507. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46508. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46509. return this;
  46510. };
  46511. /** @hidden */
  46512. TargetCamera.prototype._getViewMatrix = function () {
  46513. if (this.lockedTarget) {
  46514. this.setTarget(this._getLockedTargetPosition());
  46515. }
  46516. // Compute
  46517. this._updateCameraRotationMatrix();
  46518. // Apply the changed rotation to the upVector.
  46519. if (this._cachedRotationZ != this.rotation.z) {
  46520. this._rotateUpVectorWithCameraRotationMatrix();
  46521. this._cachedRotationZ = this.rotation.z;
  46522. }
  46523. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46524. // Computing target and final matrix
  46525. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46526. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46527. return this._viewMatrix;
  46528. };
  46529. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46530. if (this.parent) {
  46531. var parentWorldMatrix = this.parent.getWorldMatrix();
  46532. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46533. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46534. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46535. this._markSyncedWithParent();
  46536. }
  46537. else {
  46538. this._globalPosition.copyFrom(position);
  46539. this._globalCurrentTarget.copyFrom(target);
  46540. this._globalCurrentUpVector.copyFrom(up);
  46541. }
  46542. if (this.getScene().useRightHandedSystem) {
  46543. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46544. }
  46545. else {
  46546. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46547. }
  46548. };
  46549. /**
  46550. * @override
  46551. * Override Camera.createRigCamera
  46552. */
  46553. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46554. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46555. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46556. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46557. if (!this.rotationQuaternion) {
  46558. this.rotationQuaternion = new BABYLON.Quaternion();
  46559. }
  46560. rigCamera._cameraRigParams = {};
  46561. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46562. }
  46563. return rigCamera;
  46564. }
  46565. return null;
  46566. };
  46567. /**
  46568. * @hidden
  46569. * @override
  46570. * Override Camera._updateRigCameras
  46571. */
  46572. TargetCamera.prototype._updateRigCameras = function () {
  46573. var camLeft = this._rigCameras[0];
  46574. var camRight = this._rigCameras[1];
  46575. switch (this.cameraRigMode) {
  46576. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46578. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46579. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46580. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46581. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46582. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46583. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46584. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46585. camLeft.setTarget(this.getTarget());
  46586. camRight.setTarget(this.getTarget());
  46587. break;
  46588. case BABYLON.Camera.RIG_MODE_VR:
  46589. if (camLeft.rotationQuaternion) {
  46590. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46591. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46592. }
  46593. else {
  46594. camLeft.rotation.copyFrom(this.rotation);
  46595. camRight.rotation.copyFrom(this.rotation);
  46596. }
  46597. camLeft.position.copyFrom(this.position);
  46598. camRight.position.copyFrom(this.position);
  46599. break;
  46600. }
  46601. _super.prototype._updateRigCameras.call(this);
  46602. };
  46603. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46604. if (!this._rigCamTransformMatrix) {
  46605. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46606. }
  46607. var target = this.getTarget();
  46608. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46609. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46610. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46611. };
  46612. TargetCamera.prototype.getClassName = function () {
  46613. return "TargetCamera";
  46614. };
  46615. __decorate([
  46616. BABYLON.serializeAsVector3()
  46617. ], TargetCamera.prototype, "rotation", void 0);
  46618. __decorate([
  46619. BABYLON.serialize()
  46620. ], TargetCamera.prototype, "speed", void 0);
  46621. __decorate([
  46622. BABYLON.serializeAsMeshReference("lockedTargetId")
  46623. ], TargetCamera.prototype, "lockedTarget", void 0);
  46624. return TargetCamera;
  46625. }(BABYLON.Camera));
  46626. BABYLON.TargetCamera = TargetCamera;
  46627. })(BABYLON || (BABYLON = {}));
  46628. //# sourceMappingURL=babylon.targetCamera.js.map
  46629. var BABYLON;
  46630. (function (BABYLON) {
  46631. var FreeCameraMouseInput = /** @class */ (function () {
  46632. function FreeCameraMouseInput(touchEnabled) {
  46633. if (touchEnabled === void 0) { touchEnabled = true; }
  46634. this.touchEnabled = touchEnabled;
  46635. this.buttons = [0, 1, 2];
  46636. this.angularSensibility = 2000.0;
  46637. this.previousPosition = null;
  46638. }
  46639. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46640. var _this = this;
  46641. var engine = this.camera.getEngine();
  46642. if (!this._pointerInput) {
  46643. this._pointerInput = function (p, s) {
  46644. var evt = p.event;
  46645. if (engine.isInVRExclusivePointerMode) {
  46646. return;
  46647. }
  46648. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46649. return;
  46650. }
  46651. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46652. return;
  46653. }
  46654. var srcElement = (evt.srcElement || evt.target);
  46655. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46656. try {
  46657. srcElement.setPointerCapture(evt.pointerId);
  46658. }
  46659. catch (e) {
  46660. //Nothing to do with the error. Execution will continue.
  46661. }
  46662. _this.previousPosition = {
  46663. x: evt.clientX,
  46664. y: evt.clientY
  46665. };
  46666. if (!noPreventDefault) {
  46667. evt.preventDefault();
  46668. element.focus();
  46669. }
  46670. }
  46671. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46672. try {
  46673. srcElement.releasePointerCapture(evt.pointerId);
  46674. }
  46675. catch (e) {
  46676. //Nothing to do with the error.
  46677. }
  46678. _this.previousPosition = null;
  46679. if (!noPreventDefault) {
  46680. evt.preventDefault();
  46681. }
  46682. }
  46683. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46684. if (!_this.previousPosition || engine.isPointerLock) {
  46685. return;
  46686. }
  46687. var offsetX = evt.clientX - _this.previousPosition.x;
  46688. if (_this.camera.getScene().useRightHandedSystem)
  46689. offsetX *= -1;
  46690. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46691. offsetX *= -1;
  46692. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46693. var offsetY = evt.clientY - _this.previousPosition.y;
  46694. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46695. _this.previousPosition = {
  46696. x: evt.clientX,
  46697. y: evt.clientY
  46698. };
  46699. if (!noPreventDefault) {
  46700. evt.preventDefault();
  46701. }
  46702. }
  46703. };
  46704. }
  46705. this._onMouseMove = function (evt) {
  46706. if (!engine.isPointerLock) {
  46707. return;
  46708. }
  46709. if (engine.isInVRExclusivePointerMode) {
  46710. return;
  46711. }
  46712. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46713. if (_this.camera.getScene().useRightHandedSystem)
  46714. offsetX *= -1;
  46715. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46716. offsetX *= -1;
  46717. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46718. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46719. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46720. _this.previousPosition = null;
  46721. if (!noPreventDefault) {
  46722. evt.preventDefault();
  46723. }
  46724. };
  46725. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46726. element.addEventListener("mousemove", this._onMouseMove, false);
  46727. };
  46728. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46729. if (this._observer && element) {
  46730. this.camera.getScene().onPointerObservable.remove(this._observer);
  46731. if (this._onMouseMove) {
  46732. element.removeEventListener("mousemove", this._onMouseMove);
  46733. }
  46734. this._observer = null;
  46735. this._onMouseMove = null;
  46736. this.previousPosition = null;
  46737. }
  46738. };
  46739. FreeCameraMouseInput.prototype.getClassName = function () {
  46740. return "FreeCameraMouseInput";
  46741. };
  46742. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46743. return "mouse";
  46744. };
  46745. __decorate([
  46746. BABYLON.serialize()
  46747. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46748. __decorate([
  46749. BABYLON.serialize()
  46750. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46751. return FreeCameraMouseInput;
  46752. }());
  46753. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46754. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46755. })(BABYLON || (BABYLON = {}));
  46756. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46757. var BABYLON;
  46758. (function (BABYLON) {
  46759. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46760. function FreeCameraKeyboardMoveInput() {
  46761. this._keys = new Array();
  46762. this.keysUp = [38];
  46763. this.keysDown = [40];
  46764. this.keysLeft = [37];
  46765. this.keysRight = [39];
  46766. }
  46767. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46768. var _this = this;
  46769. if (this._onCanvasBlurObserver) {
  46770. return;
  46771. }
  46772. this._scene = this.camera.getScene();
  46773. this._engine = this._scene.getEngine();
  46774. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46775. _this._keys = [];
  46776. });
  46777. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46778. var evt = info.event;
  46779. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46780. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46781. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46782. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46783. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46784. var index = _this._keys.indexOf(evt.keyCode);
  46785. if (index === -1) {
  46786. _this._keys.push(evt.keyCode);
  46787. }
  46788. if (!noPreventDefault) {
  46789. evt.preventDefault();
  46790. }
  46791. }
  46792. }
  46793. else {
  46794. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46795. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46796. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46797. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46798. var index = _this._keys.indexOf(evt.keyCode);
  46799. if (index >= 0) {
  46800. _this._keys.splice(index, 1);
  46801. }
  46802. if (!noPreventDefault) {
  46803. evt.preventDefault();
  46804. }
  46805. }
  46806. }
  46807. });
  46808. };
  46809. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46810. if (this._scene) {
  46811. if (this._onKeyboardObserver) {
  46812. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46813. }
  46814. if (this._onCanvasBlurObserver) {
  46815. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46816. }
  46817. this._onKeyboardObserver = null;
  46818. this._onCanvasBlurObserver = null;
  46819. }
  46820. this._keys = [];
  46821. };
  46822. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46823. if (this._onKeyboardObserver) {
  46824. var camera = this.camera;
  46825. // Keyboard
  46826. for (var index = 0; index < this._keys.length; index++) {
  46827. var keyCode = this._keys[index];
  46828. var speed = camera._computeLocalCameraSpeed();
  46829. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46830. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46831. }
  46832. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46833. camera._localDirection.copyFromFloats(0, 0, speed);
  46834. }
  46835. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46836. camera._localDirection.copyFromFloats(speed, 0, 0);
  46837. }
  46838. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46839. camera._localDirection.copyFromFloats(0, 0, -speed);
  46840. }
  46841. if (camera.getScene().useRightHandedSystem) {
  46842. camera._localDirection.z *= -1;
  46843. }
  46844. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46845. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46846. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46847. }
  46848. }
  46849. };
  46850. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46851. return "FreeCameraKeyboardMoveInput";
  46852. };
  46853. /** @hidden */
  46854. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46855. this._keys = [];
  46856. };
  46857. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46858. return "keyboard";
  46859. };
  46860. __decorate([
  46861. BABYLON.serialize()
  46862. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46863. __decorate([
  46864. BABYLON.serialize()
  46865. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46866. __decorate([
  46867. BABYLON.serialize()
  46868. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46869. __decorate([
  46870. BABYLON.serialize()
  46871. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46872. return FreeCameraKeyboardMoveInput;
  46873. }());
  46874. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46875. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46876. })(BABYLON || (BABYLON = {}));
  46877. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46878. var BABYLON;
  46879. (function (BABYLON) {
  46880. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46881. __extends(FreeCameraInputsManager, _super);
  46882. function FreeCameraInputsManager(camera) {
  46883. return _super.call(this, camera) || this;
  46884. }
  46885. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46886. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46887. return this;
  46888. };
  46889. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46890. if (touchEnabled === void 0) { touchEnabled = true; }
  46891. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46892. return this;
  46893. };
  46894. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46895. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46896. return this;
  46897. };
  46898. FreeCameraInputsManager.prototype.addTouch = function () {
  46899. this.add(new BABYLON.FreeCameraTouchInput());
  46900. return this;
  46901. };
  46902. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46903. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46904. return this;
  46905. };
  46906. return FreeCameraInputsManager;
  46907. }(BABYLON.CameraInputsManager));
  46908. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46909. })(BABYLON || (BABYLON = {}));
  46910. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46911. var BABYLON;
  46912. (function (BABYLON) {
  46913. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46914. // Forcing to use the Universal camera
  46915. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46916. });
  46917. var FreeCamera = /** @class */ (function (_super) {
  46918. __extends(FreeCamera, _super);
  46919. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46920. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46921. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46922. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46923. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46924. _this.checkCollisions = false;
  46925. _this.applyGravity = false;
  46926. _this._needMoveForGravity = false;
  46927. _this._oldPosition = BABYLON.Vector3.Zero();
  46928. _this._diffPosition = BABYLON.Vector3.Zero();
  46929. _this._newPosition = BABYLON.Vector3.Zero();
  46930. // Collisions
  46931. _this._collisionMask = -1;
  46932. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46933. if (collidedMesh === void 0) { collidedMesh = null; }
  46934. //TODO move this to the collision coordinator!
  46935. if (_this.getScene().workerCollisions)
  46936. newPosition.multiplyInPlace(_this._collider._radius);
  46937. var updatePosition = function (newPos) {
  46938. _this._newPosition.copyFrom(newPos);
  46939. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46940. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46941. _this.position.addInPlace(_this._diffPosition);
  46942. if (_this.onCollide && collidedMesh) {
  46943. _this.onCollide(collidedMesh);
  46944. }
  46945. }
  46946. };
  46947. updatePosition(newPosition);
  46948. };
  46949. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46950. _this.inputs.addKeyboard().addMouse();
  46951. return _this;
  46952. }
  46953. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46954. //-- begin properties for backward compatibility for inputs
  46955. /**
  46956. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46957. * Higher values reduce sensitivity.
  46958. */
  46959. get: function () {
  46960. var mouse = this.inputs.attached["mouse"];
  46961. if (mouse)
  46962. return mouse.angularSensibility;
  46963. return 0;
  46964. },
  46965. /**
  46966. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46967. * Higher values reduce sensitivity.
  46968. */
  46969. set: function (value) {
  46970. var mouse = this.inputs.attached["mouse"];
  46971. if (mouse)
  46972. mouse.angularSensibility = value;
  46973. },
  46974. enumerable: true,
  46975. configurable: true
  46976. });
  46977. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46978. get: function () {
  46979. var keyboard = this.inputs.attached["keyboard"];
  46980. if (keyboard)
  46981. return keyboard.keysUp;
  46982. return [];
  46983. },
  46984. set: function (value) {
  46985. var keyboard = this.inputs.attached["keyboard"];
  46986. if (keyboard)
  46987. keyboard.keysUp = value;
  46988. },
  46989. enumerable: true,
  46990. configurable: true
  46991. });
  46992. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46993. get: function () {
  46994. var keyboard = this.inputs.attached["keyboard"];
  46995. if (keyboard)
  46996. return keyboard.keysDown;
  46997. return [];
  46998. },
  46999. set: function (value) {
  47000. var keyboard = this.inputs.attached["keyboard"];
  47001. if (keyboard)
  47002. keyboard.keysDown = value;
  47003. },
  47004. enumerable: true,
  47005. configurable: true
  47006. });
  47007. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47008. get: function () {
  47009. var keyboard = this.inputs.attached["keyboard"];
  47010. if (keyboard)
  47011. return keyboard.keysLeft;
  47012. return [];
  47013. },
  47014. set: function (value) {
  47015. var keyboard = this.inputs.attached["keyboard"];
  47016. if (keyboard)
  47017. keyboard.keysLeft = value;
  47018. },
  47019. enumerable: true,
  47020. configurable: true
  47021. });
  47022. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47023. get: function () {
  47024. var keyboard = this.inputs.attached["keyboard"];
  47025. if (keyboard)
  47026. return keyboard.keysRight;
  47027. return [];
  47028. },
  47029. set: function (value) {
  47030. var keyboard = this.inputs.attached["keyboard"];
  47031. if (keyboard)
  47032. keyboard.keysRight = value;
  47033. },
  47034. enumerable: true,
  47035. configurable: true
  47036. });
  47037. // Controls
  47038. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47039. this.inputs.attachElement(element, noPreventDefault);
  47040. };
  47041. FreeCamera.prototype.detachControl = function (element) {
  47042. this.inputs.detachElement(element);
  47043. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47044. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47045. };
  47046. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47047. get: function () {
  47048. return this._collisionMask;
  47049. },
  47050. set: function (mask) {
  47051. this._collisionMask = !isNaN(mask) ? mask : -1;
  47052. },
  47053. enumerable: true,
  47054. configurable: true
  47055. });
  47056. /** @hidden */
  47057. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47058. var globalPosition;
  47059. if (this.parent) {
  47060. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47061. }
  47062. else {
  47063. globalPosition = this.position;
  47064. }
  47065. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47066. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47067. if (!this._collider) {
  47068. this._collider = new BABYLON.Collider();
  47069. }
  47070. this._collider._radius = this.ellipsoid;
  47071. this._collider.collisionMask = this._collisionMask;
  47072. //no need for clone, as long as gravity is not on.
  47073. var actualDisplacement = displacement;
  47074. //add gravity to the direction to prevent the dual-collision checking
  47075. if (this.applyGravity) {
  47076. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47077. actualDisplacement = displacement.add(this.getScene().gravity);
  47078. }
  47079. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47080. };
  47081. /** @hidden */
  47082. FreeCamera.prototype._checkInputs = function () {
  47083. if (!this._localDirection) {
  47084. this._localDirection = BABYLON.Vector3.Zero();
  47085. this._transformedDirection = BABYLON.Vector3.Zero();
  47086. }
  47087. this.inputs.checkInputs();
  47088. _super.prototype._checkInputs.call(this);
  47089. };
  47090. /** @hidden */
  47091. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47092. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47093. };
  47094. /** @hidden */
  47095. FreeCamera.prototype._updatePosition = function () {
  47096. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47097. this._collideWithWorld(this.cameraDirection);
  47098. }
  47099. else {
  47100. _super.prototype._updatePosition.call(this);
  47101. }
  47102. };
  47103. FreeCamera.prototype.dispose = function () {
  47104. this.inputs.clear();
  47105. _super.prototype.dispose.call(this);
  47106. };
  47107. FreeCamera.prototype.getClassName = function () {
  47108. return "FreeCamera";
  47109. };
  47110. __decorate([
  47111. BABYLON.serializeAsVector3()
  47112. ], FreeCamera.prototype, "ellipsoid", void 0);
  47113. __decorate([
  47114. BABYLON.serializeAsVector3()
  47115. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47116. __decorate([
  47117. BABYLON.serialize()
  47118. ], FreeCamera.prototype, "checkCollisions", void 0);
  47119. __decorate([
  47120. BABYLON.serialize()
  47121. ], FreeCamera.prototype, "applyGravity", void 0);
  47122. return FreeCamera;
  47123. }(BABYLON.TargetCamera));
  47124. BABYLON.FreeCamera = FreeCamera;
  47125. })(BABYLON || (BABYLON = {}));
  47126. //# sourceMappingURL=babylon.freeCamera.js.map
  47127. var BABYLON;
  47128. (function (BABYLON) {
  47129. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47130. function ArcRotateCameraKeyboardMoveInput() {
  47131. this._keys = new Array();
  47132. this.keysUp = [38];
  47133. this.keysDown = [40];
  47134. this.keysLeft = [37];
  47135. this.keysRight = [39];
  47136. this.keysReset = [220];
  47137. this.panningSensibility = 50.0;
  47138. this.zoomingSensibility = 25.0;
  47139. this.useAltToZoom = true;
  47140. }
  47141. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47142. var _this = this;
  47143. if (this._onCanvasBlurObserver) {
  47144. return;
  47145. }
  47146. this._scene = this.camera.getScene();
  47147. this._engine = this._scene.getEngine();
  47148. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47149. _this._keys = [];
  47150. });
  47151. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47152. var evt = info.event;
  47153. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47154. _this._ctrlPressed = evt.ctrlKey;
  47155. _this._altPressed = evt.altKey;
  47156. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47157. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47158. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47159. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47160. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47161. var index = _this._keys.indexOf(evt.keyCode);
  47162. if (index === -1) {
  47163. _this._keys.push(evt.keyCode);
  47164. }
  47165. if (evt.preventDefault) {
  47166. if (!noPreventDefault) {
  47167. evt.preventDefault();
  47168. }
  47169. }
  47170. }
  47171. }
  47172. else {
  47173. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47174. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47175. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47176. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47177. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47178. var index = _this._keys.indexOf(evt.keyCode);
  47179. if (index >= 0) {
  47180. _this._keys.splice(index, 1);
  47181. }
  47182. if (evt.preventDefault) {
  47183. if (!noPreventDefault) {
  47184. evt.preventDefault();
  47185. }
  47186. }
  47187. }
  47188. }
  47189. });
  47190. };
  47191. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47192. if (this._scene) {
  47193. if (this._onKeyboardObserver) {
  47194. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47195. }
  47196. if (this._onCanvasBlurObserver) {
  47197. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47198. }
  47199. this._onKeyboardObserver = null;
  47200. this._onCanvasBlurObserver = null;
  47201. }
  47202. this._keys = [];
  47203. };
  47204. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47205. if (this._onKeyboardObserver) {
  47206. var camera = this.camera;
  47207. for (var index = 0; index < this._keys.length; index++) {
  47208. var keyCode = this._keys[index];
  47209. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47210. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47211. camera.inertialPanningX -= 1 / this.panningSensibility;
  47212. }
  47213. else {
  47214. camera.inertialAlphaOffset -= 0.01;
  47215. }
  47216. }
  47217. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47218. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47219. camera.inertialPanningY += 1 / this.panningSensibility;
  47220. }
  47221. else if (this._altPressed && this.useAltToZoom) {
  47222. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47223. }
  47224. else {
  47225. camera.inertialBetaOffset -= 0.01;
  47226. }
  47227. }
  47228. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47229. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47230. camera.inertialPanningX += 1 / this.panningSensibility;
  47231. }
  47232. else {
  47233. camera.inertialAlphaOffset += 0.01;
  47234. }
  47235. }
  47236. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47237. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47238. camera.inertialPanningY -= 1 / this.panningSensibility;
  47239. }
  47240. else if (this._altPressed && this.useAltToZoom) {
  47241. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47242. }
  47243. else {
  47244. camera.inertialBetaOffset += 0.01;
  47245. }
  47246. }
  47247. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47248. camera.restoreState();
  47249. }
  47250. }
  47251. }
  47252. };
  47253. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47254. return "ArcRotateCameraKeyboardMoveInput";
  47255. };
  47256. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47257. return "keyboard";
  47258. };
  47259. __decorate([
  47260. BABYLON.serialize()
  47261. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47262. __decorate([
  47263. BABYLON.serialize()
  47264. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47268. __decorate([
  47269. BABYLON.serialize()
  47270. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47271. __decorate([
  47272. BABYLON.serialize()
  47273. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47274. __decorate([
  47275. BABYLON.serialize()
  47276. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47277. __decorate([
  47278. BABYLON.serialize()
  47279. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47280. __decorate([
  47281. BABYLON.serialize()
  47282. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47283. return ArcRotateCameraKeyboardMoveInput;
  47284. }());
  47285. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47286. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47287. })(BABYLON || (BABYLON = {}));
  47288. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47289. var BABYLON;
  47290. (function (BABYLON) {
  47291. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47292. function ArcRotateCameraMouseWheelInput() {
  47293. this.wheelPrecision = 3.0;
  47294. /**
  47295. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47296. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47297. */
  47298. this.wheelDeltaPercentage = 0;
  47299. }
  47300. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47301. var _this = this;
  47302. this._wheel = function (p, s) {
  47303. //sanity check - this should be a PointerWheel event.
  47304. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47305. return;
  47306. var event = p.event;
  47307. var delta = 0;
  47308. if (event.wheelDelta) {
  47309. if (_this.wheelDeltaPercentage) {
  47310. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47311. if (event.wheelDelta > 0) {
  47312. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47313. }
  47314. else {
  47315. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47316. }
  47317. }
  47318. else {
  47319. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47320. }
  47321. }
  47322. else if (event.detail) {
  47323. delta = -event.detail / _this.wheelPrecision;
  47324. }
  47325. if (delta)
  47326. _this.camera.inertialRadiusOffset += delta;
  47327. if (event.preventDefault) {
  47328. if (!noPreventDefault) {
  47329. event.preventDefault();
  47330. }
  47331. }
  47332. };
  47333. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47334. };
  47335. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47336. if (this._observer && element) {
  47337. this.camera.getScene().onPointerObservable.remove(this._observer);
  47338. this._observer = null;
  47339. this._wheel = null;
  47340. }
  47341. };
  47342. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47343. return "ArcRotateCameraMouseWheelInput";
  47344. };
  47345. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47346. return "mousewheel";
  47347. };
  47348. __decorate([
  47349. BABYLON.serialize()
  47350. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47351. __decorate([
  47352. BABYLON.serialize()
  47353. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47354. return ArcRotateCameraMouseWheelInput;
  47355. }());
  47356. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47357. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47358. })(BABYLON || (BABYLON = {}));
  47359. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47360. var BABYLON;
  47361. (function (BABYLON) {
  47362. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47363. function ArcRotateCameraPointersInput() {
  47364. this.buttons = [0, 1, 2];
  47365. this.angularSensibilityX = 1000.0;
  47366. this.angularSensibilityY = 1000.0;
  47367. this.pinchPrecision = 12.0;
  47368. /**
  47369. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47370. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47371. */
  47372. this.pinchDeltaPercentage = 0;
  47373. this.panningSensibility = 1000.0;
  47374. this.multiTouchPanning = true;
  47375. this.multiTouchPanAndZoom = true;
  47376. this._isPanClick = false;
  47377. this.pinchInwards = true;
  47378. }
  47379. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47380. var _this = this;
  47381. var engine = this.camera.getEngine();
  47382. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47383. var pointA = null;
  47384. var pointB = null;
  47385. var previousPinchSquaredDistance = 0;
  47386. var initialDistance = 0;
  47387. var twoFingerActivityCount = 0;
  47388. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47389. this._pointerInput = function (p, s) {
  47390. var evt = p.event;
  47391. var isTouch = p.event.pointerType === "touch";
  47392. if (engine.isInVRExclusivePointerMode) {
  47393. return;
  47394. }
  47395. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47396. return;
  47397. }
  47398. var srcElement = (evt.srcElement || evt.target);
  47399. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47400. try {
  47401. srcElement.setPointerCapture(evt.pointerId);
  47402. }
  47403. catch (e) {
  47404. //Nothing to do with the error. Execution will continue.
  47405. }
  47406. // Manage panning with pan button click
  47407. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47408. // manage pointers
  47409. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47410. if (pointA === null) {
  47411. pointA = cacheSoloPointer;
  47412. }
  47413. else if (pointB === null) {
  47414. pointB = cacheSoloPointer;
  47415. }
  47416. if (!noPreventDefault) {
  47417. evt.preventDefault();
  47418. element.focus();
  47419. }
  47420. }
  47421. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47422. _this.camera.restoreState();
  47423. }
  47424. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47425. try {
  47426. srcElement.releasePointerCapture(evt.pointerId);
  47427. }
  47428. catch (e) {
  47429. //Nothing to do with the error.
  47430. }
  47431. cacheSoloPointer = null;
  47432. previousPinchSquaredDistance = 0;
  47433. previousMultiTouchPanPosition.isPaning = false;
  47434. previousMultiTouchPanPosition.isPinching = false;
  47435. twoFingerActivityCount = 0;
  47436. initialDistance = 0;
  47437. if (!isTouch) {
  47438. pointB = null; // Mouse and pen are mono pointer
  47439. }
  47440. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47441. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47442. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47443. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47444. if (engine._badOS) {
  47445. pointA = pointB = null;
  47446. }
  47447. else {
  47448. //only remove the impacted pointer in case of multitouch allowing on most
  47449. //platforms switching from rotate to zoom and pan seamlessly.
  47450. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47451. pointA = pointB;
  47452. pointB = null;
  47453. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47454. }
  47455. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47456. pointB = null;
  47457. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47458. }
  47459. else {
  47460. pointA = pointB = null;
  47461. }
  47462. }
  47463. if (!noPreventDefault) {
  47464. evt.preventDefault();
  47465. }
  47466. }
  47467. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47468. if (!noPreventDefault) {
  47469. evt.preventDefault();
  47470. }
  47471. // One button down
  47472. if (pointA && pointB === null && cacheSoloPointer) {
  47473. if (_this.panningSensibility !== 0 &&
  47474. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47475. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47476. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47477. }
  47478. else {
  47479. var offsetX = evt.clientX - cacheSoloPointer.x;
  47480. var offsetY = evt.clientY - cacheSoloPointer.y;
  47481. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47482. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47483. }
  47484. cacheSoloPointer.x = evt.clientX;
  47485. cacheSoloPointer.y = evt.clientY;
  47486. }
  47487. // Two buttons down: pinch/pan
  47488. else if (pointA && pointB) {
  47489. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47490. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47491. ed.x = evt.clientX;
  47492. ed.y = evt.clientY;
  47493. var direction = _this.pinchInwards ? 1 : -1;
  47494. var distX = pointA.x - pointB.x;
  47495. var distY = pointA.y - pointB.y;
  47496. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47497. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47498. if (previousPinchSquaredDistance === 0) {
  47499. initialDistance = pinchDistance;
  47500. previousPinchSquaredDistance = pinchSquaredDistance;
  47501. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47502. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47503. return;
  47504. }
  47505. if (_this.multiTouchPanAndZoom) {
  47506. if (_this.pinchDeltaPercentage) {
  47507. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47508. }
  47509. else {
  47510. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47511. (_this.pinchPrecision *
  47512. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47513. direction);
  47514. }
  47515. if (_this.panningSensibility !== 0) {
  47516. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47517. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47518. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47519. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47520. previousMultiTouchPanPosition.x = pointersCenterX;
  47521. previousMultiTouchPanPosition.y = pointersCenterY;
  47522. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47523. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47524. }
  47525. }
  47526. else {
  47527. twoFingerActivityCount++;
  47528. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47529. if (_this.pinchDeltaPercentage) {
  47530. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47531. }
  47532. else {
  47533. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47534. (_this.pinchPrecision *
  47535. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47536. direction);
  47537. }
  47538. previousMultiTouchPanPosition.isPaning = false;
  47539. previousMultiTouchPanPosition.isPinching = true;
  47540. }
  47541. else {
  47542. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47543. if (!previousMultiTouchPanPosition.isPaning) {
  47544. previousMultiTouchPanPosition.isPaning = true;
  47545. previousMultiTouchPanPosition.isPinching = false;
  47546. previousMultiTouchPanPosition.x = ed.x;
  47547. previousMultiTouchPanPosition.y = ed.y;
  47548. return;
  47549. }
  47550. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47551. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47552. }
  47553. }
  47554. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47555. previousMultiTouchPanPosition.x = ed.x;
  47556. previousMultiTouchPanPosition.y = ed.y;
  47557. }
  47558. }
  47559. previousPinchSquaredDistance = pinchSquaredDistance;
  47560. }
  47561. }
  47562. };
  47563. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47564. this._onContextMenu = function (evt) {
  47565. evt.preventDefault();
  47566. };
  47567. if (!this.camera._useCtrlForPanning) {
  47568. element.addEventListener("contextmenu", this._onContextMenu, false);
  47569. }
  47570. this._onLostFocus = function () {
  47571. //this._keys = [];
  47572. pointA = pointB = null;
  47573. previousPinchSquaredDistance = 0;
  47574. previousMultiTouchPanPosition.isPaning = false;
  47575. previousMultiTouchPanPosition.isPinching = false;
  47576. twoFingerActivityCount = 0;
  47577. cacheSoloPointer = null;
  47578. initialDistance = 0;
  47579. };
  47580. this._onMouseMove = function (evt) {
  47581. if (!engine.isPointerLock) {
  47582. return;
  47583. }
  47584. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47585. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47586. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47587. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47588. if (!noPreventDefault) {
  47589. evt.preventDefault();
  47590. }
  47591. };
  47592. this._onGestureStart = function (e) {
  47593. if (window.MSGesture === undefined) {
  47594. return;
  47595. }
  47596. if (!_this._MSGestureHandler) {
  47597. _this._MSGestureHandler = new MSGesture();
  47598. _this._MSGestureHandler.target = element;
  47599. }
  47600. _this._MSGestureHandler.addPointer(e.pointerId);
  47601. };
  47602. this._onGesture = function (e) {
  47603. _this.camera.radius *= e.scale;
  47604. if (e.preventDefault) {
  47605. if (!noPreventDefault) {
  47606. e.stopPropagation();
  47607. e.preventDefault();
  47608. }
  47609. }
  47610. };
  47611. element.addEventListener("mousemove", this._onMouseMove, false);
  47612. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47613. element.addEventListener("MSGestureChange", this._onGesture, false);
  47614. BABYLON.Tools.RegisterTopRootEvents([
  47615. { name: "blur", handler: this._onLostFocus }
  47616. ]);
  47617. };
  47618. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47619. if (this._onLostFocus) {
  47620. BABYLON.Tools.UnregisterTopRootEvents([
  47621. { name: "blur", handler: this._onLostFocus }
  47622. ]);
  47623. }
  47624. if (element && this._observer) {
  47625. this.camera.getScene().onPointerObservable.remove(this._observer);
  47626. this._observer = null;
  47627. if (this._onContextMenu) {
  47628. element.removeEventListener("contextmenu", this._onContextMenu);
  47629. }
  47630. if (this._onMouseMove) {
  47631. element.removeEventListener("mousemove", this._onMouseMove);
  47632. }
  47633. if (this._onGestureStart) {
  47634. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47635. }
  47636. if (this._onGesture) {
  47637. element.removeEventListener("MSGestureChange", this._onGesture);
  47638. }
  47639. this._isPanClick = false;
  47640. this.pinchInwards = true;
  47641. this._onMouseMove = null;
  47642. this._onGestureStart = null;
  47643. this._onGesture = null;
  47644. this._MSGestureHandler = null;
  47645. this._onLostFocus = null;
  47646. this._onContextMenu = null;
  47647. }
  47648. };
  47649. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47650. return "ArcRotateCameraPointersInput";
  47651. };
  47652. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47653. return "pointers";
  47654. };
  47655. __decorate([
  47656. BABYLON.serialize()
  47657. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47658. __decorate([
  47659. BABYLON.serialize()
  47660. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47661. __decorate([
  47662. BABYLON.serialize()
  47663. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47664. __decorate([
  47665. BABYLON.serialize()
  47666. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47667. __decorate([
  47668. BABYLON.serialize()
  47669. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47670. __decorate([
  47671. BABYLON.serialize()
  47672. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47673. __decorate([
  47674. BABYLON.serialize()
  47675. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47676. __decorate([
  47677. BABYLON.serialize()
  47678. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47679. return ArcRotateCameraPointersInput;
  47680. }());
  47681. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47682. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47683. })(BABYLON || (BABYLON = {}));
  47684. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47685. var BABYLON;
  47686. (function (BABYLON) {
  47687. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47688. __extends(ArcRotateCameraInputsManager, _super);
  47689. function ArcRotateCameraInputsManager(camera) {
  47690. return _super.call(this, camera) || this;
  47691. }
  47692. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47693. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47694. return this;
  47695. };
  47696. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47697. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47698. return this;
  47699. };
  47700. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47701. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47702. return this;
  47703. };
  47704. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47705. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47706. return this;
  47707. };
  47708. return ArcRotateCameraInputsManager;
  47709. }(BABYLON.CameraInputsManager));
  47710. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47711. })(BABYLON || (BABYLON = {}));
  47712. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47713. var BABYLON;
  47714. (function (BABYLON) {
  47715. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47716. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47717. });
  47718. var ArcRotateCamera = /** @class */ (function (_super) {
  47719. __extends(ArcRotateCamera, _super);
  47720. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47721. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47722. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47723. _this.inertialAlphaOffset = 0;
  47724. _this.inertialBetaOffset = 0;
  47725. _this.inertialRadiusOffset = 0;
  47726. _this.lowerAlphaLimit = null;
  47727. _this.upperAlphaLimit = null;
  47728. _this.lowerBetaLimit = 0.01;
  47729. _this.upperBetaLimit = Math.PI;
  47730. _this.lowerRadiusLimit = null;
  47731. _this.upperRadiusLimit = null;
  47732. _this.inertialPanningX = 0;
  47733. _this.inertialPanningY = 0;
  47734. _this.pinchToPanMaxDistance = 20;
  47735. _this.panningDistanceLimit = null;
  47736. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47737. _this.panningInertia = 0.9;
  47738. //-- end properties for backward compatibility for inputs
  47739. _this.zoomOnFactor = 1;
  47740. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47741. _this.allowUpsideDown = true;
  47742. /** @hidden */
  47743. _this._viewMatrix = new BABYLON.Matrix();
  47744. // Panning
  47745. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47746. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47747. _this.checkCollisions = false;
  47748. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47749. _this._previousPosition = BABYLON.Vector3.Zero();
  47750. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47751. _this._newPosition = BABYLON.Vector3.Zero();
  47752. _this._computationVector = BABYLON.Vector3.Zero();
  47753. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47754. if (collidedMesh === void 0) { collidedMesh = null; }
  47755. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47756. newPosition.multiplyInPlace(_this._collider._radius);
  47757. }
  47758. if (!collidedMesh) {
  47759. _this._previousPosition.copyFrom(_this.position);
  47760. }
  47761. else {
  47762. _this.setPosition(newPosition);
  47763. if (_this.onCollide) {
  47764. _this.onCollide(collidedMesh);
  47765. }
  47766. }
  47767. // Recompute because of constraints
  47768. var cosa = Math.cos(_this.alpha);
  47769. var sina = Math.sin(_this.alpha);
  47770. var cosb = Math.cos(_this.beta);
  47771. var sinb = Math.sin(_this.beta);
  47772. if (sinb === 0) {
  47773. sinb = 0.0001;
  47774. }
  47775. var target = _this._getTargetPosition();
  47776. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47777. target.addToRef(_this._computationVector, _this._newPosition);
  47778. _this.position.copyFrom(_this._newPosition);
  47779. var up = _this.upVector;
  47780. if (_this.allowUpsideDown && _this.beta < 0) {
  47781. up = up.clone();
  47782. up = up.negate();
  47783. }
  47784. _this._computeViewMatrix(_this.position, target, up);
  47785. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47786. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47787. _this._collisionTriggered = false;
  47788. };
  47789. _this._target = BABYLON.Vector3.Zero();
  47790. if (target) {
  47791. _this.setTarget(target);
  47792. }
  47793. _this.alpha = alpha;
  47794. _this.beta = beta;
  47795. _this.radius = radius;
  47796. _this.getViewMatrix();
  47797. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47798. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47799. return _this;
  47800. }
  47801. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47802. get: function () {
  47803. return this._target;
  47804. },
  47805. set: function (value) {
  47806. this.setTarget(value);
  47807. },
  47808. enumerable: true,
  47809. configurable: true
  47810. });
  47811. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47812. //-- begin properties for backward compatibility for inputs
  47813. get: function () {
  47814. var pointers = this.inputs.attached["pointers"];
  47815. if (pointers)
  47816. return pointers.angularSensibilityX;
  47817. return 0;
  47818. },
  47819. set: function (value) {
  47820. var pointers = this.inputs.attached["pointers"];
  47821. if (pointers) {
  47822. pointers.angularSensibilityX = value;
  47823. }
  47824. },
  47825. enumerable: true,
  47826. configurable: true
  47827. });
  47828. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47829. get: function () {
  47830. var pointers = this.inputs.attached["pointers"];
  47831. if (pointers)
  47832. return pointers.angularSensibilityY;
  47833. return 0;
  47834. },
  47835. set: function (value) {
  47836. var pointers = this.inputs.attached["pointers"];
  47837. if (pointers) {
  47838. pointers.angularSensibilityY = value;
  47839. }
  47840. },
  47841. enumerable: true,
  47842. configurable: true
  47843. });
  47844. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47845. get: function () {
  47846. var pointers = this.inputs.attached["pointers"];
  47847. if (pointers)
  47848. return pointers.pinchPrecision;
  47849. return 0;
  47850. },
  47851. set: function (value) {
  47852. var pointers = this.inputs.attached["pointers"];
  47853. if (pointers) {
  47854. pointers.pinchPrecision = value;
  47855. }
  47856. },
  47857. enumerable: true,
  47858. configurable: true
  47859. });
  47860. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47861. get: function () {
  47862. var pointers = this.inputs.attached["pointers"];
  47863. if (pointers)
  47864. return pointers.pinchDeltaPercentage;
  47865. return 0;
  47866. },
  47867. set: function (value) {
  47868. var pointers = this.inputs.attached["pointers"];
  47869. if (pointers) {
  47870. pointers.pinchDeltaPercentage = value;
  47871. }
  47872. },
  47873. enumerable: true,
  47874. configurable: true
  47875. });
  47876. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47877. get: function () {
  47878. var pointers = this.inputs.attached["pointers"];
  47879. if (pointers)
  47880. return pointers.panningSensibility;
  47881. return 0;
  47882. },
  47883. set: function (value) {
  47884. var pointers = this.inputs.attached["pointers"];
  47885. if (pointers) {
  47886. pointers.panningSensibility = value;
  47887. }
  47888. },
  47889. enumerable: true,
  47890. configurable: true
  47891. });
  47892. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47893. get: function () {
  47894. var keyboard = this.inputs.attached["keyboard"];
  47895. if (keyboard)
  47896. return keyboard.keysUp;
  47897. return [];
  47898. },
  47899. set: function (value) {
  47900. var keyboard = this.inputs.attached["keyboard"];
  47901. if (keyboard)
  47902. keyboard.keysUp = value;
  47903. },
  47904. enumerable: true,
  47905. configurable: true
  47906. });
  47907. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47908. get: function () {
  47909. var keyboard = this.inputs.attached["keyboard"];
  47910. if (keyboard)
  47911. return keyboard.keysDown;
  47912. return [];
  47913. },
  47914. set: function (value) {
  47915. var keyboard = this.inputs.attached["keyboard"];
  47916. if (keyboard)
  47917. keyboard.keysDown = value;
  47918. },
  47919. enumerable: true,
  47920. configurable: true
  47921. });
  47922. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47923. get: function () {
  47924. var keyboard = this.inputs.attached["keyboard"];
  47925. if (keyboard)
  47926. return keyboard.keysLeft;
  47927. return [];
  47928. },
  47929. set: function (value) {
  47930. var keyboard = this.inputs.attached["keyboard"];
  47931. if (keyboard)
  47932. keyboard.keysLeft = value;
  47933. },
  47934. enumerable: true,
  47935. configurable: true
  47936. });
  47937. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47938. get: function () {
  47939. var keyboard = this.inputs.attached["keyboard"];
  47940. if (keyboard)
  47941. return keyboard.keysRight;
  47942. return [];
  47943. },
  47944. set: function (value) {
  47945. var keyboard = this.inputs.attached["keyboard"];
  47946. if (keyboard)
  47947. keyboard.keysRight = value;
  47948. },
  47949. enumerable: true,
  47950. configurable: true
  47951. });
  47952. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47953. get: function () {
  47954. var mousewheel = this.inputs.attached["mousewheel"];
  47955. if (mousewheel)
  47956. return mousewheel.wheelPrecision;
  47957. return 0;
  47958. },
  47959. set: function (value) {
  47960. var mousewheel = this.inputs.attached["mousewheel"];
  47961. if (mousewheel)
  47962. mousewheel.wheelPrecision = value;
  47963. },
  47964. enumerable: true,
  47965. configurable: true
  47966. });
  47967. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47968. get: function () {
  47969. var mousewheel = this.inputs.attached["mousewheel"];
  47970. if (mousewheel)
  47971. return mousewheel.wheelDeltaPercentage;
  47972. return 0;
  47973. },
  47974. set: function (value) {
  47975. var mousewheel = this.inputs.attached["mousewheel"];
  47976. if (mousewheel)
  47977. mousewheel.wheelDeltaPercentage = value;
  47978. },
  47979. enumerable: true,
  47980. configurable: true
  47981. });
  47982. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47983. get: function () {
  47984. return this._bouncingBehavior;
  47985. },
  47986. enumerable: true,
  47987. configurable: true
  47988. });
  47989. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47990. get: function () {
  47991. return this._bouncingBehavior != null;
  47992. },
  47993. set: function (value) {
  47994. if (value === this.useBouncingBehavior) {
  47995. return;
  47996. }
  47997. if (value) {
  47998. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47999. this.addBehavior(this._bouncingBehavior);
  48000. }
  48001. else if (this._bouncingBehavior) {
  48002. this.removeBehavior(this._bouncingBehavior);
  48003. this._bouncingBehavior = null;
  48004. }
  48005. },
  48006. enumerable: true,
  48007. configurable: true
  48008. });
  48009. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48010. get: function () {
  48011. return this._framingBehavior;
  48012. },
  48013. enumerable: true,
  48014. configurable: true
  48015. });
  48016. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48017. get: function () {
  48018. return this._framingBehavior != null;
  48019. },
  48020. set: function (value) {
  48021. if (value === this.useFramingBehavior) {
  48022. return;
  48023. }
  48024. if (value) {
  48025. this._framingBehavior = new BABYLON.FramingBehavior();
  48026. this.addBehavior(this._framingBehavior);
  48027. }
  48028. else if (this._framingBehavior) {
  48029. this.removeBehavior(this._framingBehavior);
  48030. this._framingBehavior = null;
  48031. }
  48032. },
  48033. enumerable: true,
  48034. configurable: true
  48035. });
  48036. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48037. get: function () {
  48038. return this._autoRotationBehavior;
  48039. },
  48040. enumerable: true,
  48041. configurable: true
  48042. });
  48043. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48044. get: function () {
  48045. return this._autoRotationBehavior != null;
  48046. },
  48047. set: function (value) {
  48048. if (value === this.useAutoRotationBehavior) {
  48049. return;
  48050. }
  48051. if (value) {
  48052. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48053. this.addBehavior(this._autoRotationBehavior);
  48054. }
  48055. else if (this._autoRotationBehavior) {
  48056. this.removeBehavior(this._autoRotationBehavior);
  48057. this._autoRotationBehavior = null;
  48058. }
  48059. },
  48060. enumerable: true,
  48061. configurable: true
  48062. });
  48063. // Cache
  48064. /** @hidden */
  48065. ArcRotateCamera.prototype._initCache = function () {
  48066. _super.prototype._initCache.call(this);
  48067. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48068. this._cache.alpha = undefined;
  48069. this._cache.beta = undefined;
  48070. this._cache.radius = undefined;
  48071. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48072. };
  48073. /** @hidden */
  48074. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48075. if (!ignoreParentClass) {
  48076. _super.prototype._updateCache.call(this);
  48077. }
  48078. this._cache._target.copyFrom(this._getTargetPosition());
  48079. this._cache.alpha = this.alpha;
  48080. this._cache.beta = this.beta;
  48081. this._cache.radius = this.radius;
  48082. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48083. };
  48084. ArcRotateCamera.prototype._getTargetPosition = function () {
  48085. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48086. var pos = this._targetHost.getAbsolutePosition();
  48087. if (this._targetBoundingCenter) {
  48088. pos.addToRef(this._targetBoundingCenter, this._target);
  48089. }
  48090. else {
  48091. this._target.copyFrom(pos);
  48092. }
  48093. }
  48094. var lockedTargetPosition = this._getLockedTargetPosition();
  48095. if (lockedTargetPosition) {
  48096. return lockedTargetPosition;
  48097. }
  48098. return this._target;
  48099. };
  48100. ArcRotateCamera.prototype.storeState = function () {
  48101. this._storedAlpha = this.alpha;
  48102. this._storedBeta = this.beta;
  48103. this._storedRadius = this.radius;
  48104. this._storedTarget = this._getTargetPosition().clone();
  48105. return _super.prototype.storeState.call(this);
  48106. };
  48107. /**
  48108. * @hidden
  48109. * Restored camera state. You must call storeState() first
  48110. */
  48111. ArcRotateCamera.prototype._restoreStateValues = function () {
  48112. if (!_super.prototype._restoreStateValues.call(this)) {
  48113. return false;
  48114. }
  48115. this.alpha = this._storedAlpha;
  48116. this.beta = this._storedBeta;
  48117. this.radius = this._storedRadius;
  48118. this.setTarget(this._storedTarget.clone());
  48119. this.inertialAlphaOffset = 0;
  48120. this.inertialBetaOffset = 0;
  48121. this.inertialRadiusOffset = 0;
  48122. this.inertialPanningX = 0;
  48123. this.inertialPanningY = 0;
  48124. return true;
  48125. };
  48126. // Synchronized
  48127. /** @hidden */
  48128. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48129. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48130. return false;
  48131. return this._cache._target.equals(this._getTargetPosition())
  48132. && this._cache.alpha === this.alpha
  48133. && this._cache.beta === this.beta
  48134. && this._cache.radius === this.radius
  48135. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48136. };
  48137. // Methods
  48138. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48139. var _this = this;
  48140. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48141. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48142. this._useCtrlForPanning = useCtrlForPanning;
  48143. this._panningMouseButton = panningMouseButton;
  48144. this.inputs.attachElement(element, noPreventDefault);
  48145. this._reset = function () {
  48146. _this.inertialAlphaOffset = 0;
  48147. _this.inertialBetaOffset = 0;
  48148. _this.inertialRadiusOffset = 0;
  48149. _this.inertialPanningX = 0;
  48150. _this.inertialPanningY = 0;
  48151. };
  48152. };
  48153. ArcRotateCamera.prototype.detachControl = function (element) {
  48154. this.inputs.detachElement(element);
  48155. if (this._reset) {
  48156. this._reset();
  48157. }
  48158. };
  48159. /** @hidden */
  48160. ArcRotateCamera.prototype._checkInputs = function () {
  48161. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48162. if (this._collisionTriggered) {
  48163. return;
  48164. }
  48165. this.inputs.checkInputs();
  48166. // Inertia
  48167. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48168. var inertialAlphaOffset = this.inertialAlphaOffset;
  48169. if (this.beta <= 0)
  48170. inertialAlphaOffset *= -1;
  48171. if (this.getScene().useRightHandedSystem)
  48172. inertialAlphaOffset *= -1;
  48173. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48174. inertialAlphaOffset *= -1;
  48175. this.alpha += inertialAlphaOffset;
  48176. this.beta += this.inertialBetaOffset;
  48177. this.radius -= this.inertialRadiusOffset;
  48178. this.inertialAlphaOffset *= this.inertia;
  48179. this.inertialBetaOffset *= this.inertia;
  48180. this.inertialRadiusOffset *= this.inertia;
  48181. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48182. this.inertialAlphaOffset = 0;
  48183. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48184. this.inertialBetaOffset = 0;
  48185. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48186. this.inertialRadiusOffset = 0;
  48187. }
  48188. // Panning inertia
  48189. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48190. if (!this._localDirection) {
  48191. this._localDirection = BABYLON.Vector3.Zero();
  48192. this._transformedDirection = BABYLON.Vector3.Zero();
  48193. }
  48194. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48195. this._localDirection.multiplyInPlace(this.panningAxis);
  48196. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48197. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48198. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48199. if (!this.panningAxis.y) {
  48200. this._transformedDirection.y = 0;
  48201. }
  48202. if (!this._targetHost) {
  48203. if (this.panningDistanceLimit) {
  48204. this._transformedDirection.addInPlace(this._target);
  48205. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48206. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48207. this._target.copyFrom(this._transformedDirection);
  48208. }
  48209. }
  48210. else {
  48211. this._target.addInPlace(this._transformedDirection);
  48212. }
  48213. }
  48214. this.inertialPanningX *= this.panningInertia;
  48215. this.inertialPanningY *= this.panningInertia;
  48216. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48217. this.inertialPanningX = 0;
  48218. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48219. this.inertialPanningY = 0;
  48220. }
  48221. // Limits
  48222. this._checkLimits();
  48223. _super.prototype._checkInputs.call(this);
  48224. };
  48225. ArcRotateCamera.prototype._checkLimits = function () {
  48226. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48227. if (this.allowUpsideDown && this.beta > Math.PI) {
  48228. this.beta = this.beta - (2 * Math.PI);
  48229. }
  48230. }
  48231. else {
  48232. if (this.beta < this.lowerBetaLimit) {
  48233. this.beta = this.lowerBetaLimit;
  48234. }
  48235. }
  48236. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48237. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48238. this.beta = this.beta + (2 * Math.PI);
  48239. }
  48240. }
  48241. else {
  48242. if (this.beta > this.upperBetaLimit) {
  48243. this.beta = this.upperBetaLimit;
  48244. }
  48245. }
  48246. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48247. this.alpha = this.lowerAlphaLimit;
  48248. }
  48249. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48250. this.alpha = this.upperAlphaLimit;
  48251. }
  48252. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48253. this.radius = this.lowerRadiusLimit;
  48254. }
  48255. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48256. this.radius = this.upperRadiusLimit;
  48257. }
  48258. };
  48259. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48260. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48261. this.radius = this._computationVector.length();
  48262. if (this.radius === 0) {
  48263. this.radius = 0.0001; // Just to avoid division by zero
  48264. }
  48265. // Alpha
  48266. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48267. if (this._computationVector.z < 0) {
  48268. this.alpha = 2 * Math.PI - this.alpha;
  48269. }
  48270. // Beta
  48271. this.beta = Math.acos(this._computationVector.y / this.radius);
  48272. this._checkLimits();
  48273. };
  48274. ArcRotateCamera.prototype.setPosition = function (position) {
  48275. if (this.position.equals(position)) {
  48276. return;
  48277. }
  48278. this.position.copyFrom(position);
  48279. this.rebuildAnglesAndRadius();
  48280. };
  48281. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48282. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48283. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48284. if (target.getBoundingInfo) {
  48285. if (toBoundingCenter) {
  48286. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48287. }
  48288. else {
  48289. this._targetBoundingCenter = null;
  48290. }
  48291. this._targetHost = target;
  48292. this._target = this._getTargetPosition();
  48293. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48294. }
  48295. else {
  48296. var newTarget = target;
  48297. var currentTarget = this._getTargetPosition();
  48298. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48299. return;
  48300. }
  48301. this._targetHost = null;
  48302. this._target = newTarget;
  48303. this._targetBoundingCenter = null;
  48304. this.onMeshTargetChangedObservable.notifyObservers(null);
  48305. }
  48306. this.rebuildAnglesAndRadius();
  48307. };
  48308. /** @hidden */
  48309. ArcRotateCamera.prototype._getViewMatrix = function () {
  48310. // Compute
  48311. var cosa = Math.cos(this.alpha);
  48312. var sina = Math.sin(this.alpha);
  48313. var cosb = Math.cos(this.beta);
  48314. var sinb = Math.sin(this.beta);
  48315. if (sinb === 0) {
  48316. sinb = 0.0001;
  48317. }
  48318. var target = this._getTargetPosition();
  48319. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48320. target.addToRef(this._computationVector, this._newPosition);
  48321. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48322. if (!this._collider) {
  48323. this._collider = new BABYLON.Collider();
  48324. }
  48325. this._collider._radius = this.collisionRadius;
  48326. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48327. this._collisionTriggered = true;
  48328. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48329. }
  48330. else {
  48331. this.position.copyFrom(this._newPosition);
  48332. var up = this.upVector;
  48333. if (this.allowUpsideDown && sinb < 0) {
  48334. up = up.clone();
  48335. up = up.negate();
  48336. }
  48337. this._computeViewMatrix(this.position, target, up);
  48338. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48339. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48340. }
  48341. this._currentTarget = target;
  48342. return this._viewMatrix;
  48343. };
  48344. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48345. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48346. meshes = meshes || this.getScene().meshes;
  48347. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48348. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48349. this.radius = distance * this.zoomOnFactor;
  48350. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48351. };
  48352. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48353. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48354. var meshesOrMinMaxVector;
  48355. var distance;
  48356. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48357. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48358. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48359. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48360. }
  48361. else { //minMaxVector and distance
  48362. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48363. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48364. distance = minMaxVectorAndDistance.distance;
  48365. }
  48366. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48367. if (!doNotUpdateMaxZ) {
  48368. this.maxZ = distance * 2;
  48369. }
  48370. };
  48371. /**
  48372. * @override
  48373. * Override Camera.createRigCamera
  48374. */
  48375. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48376. var alphaShift = 0;
  48377. switch (this.cameraRigMode) {
  48378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48380. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48381. case BABYLON.Camera.RIG_MODE_VR:
  48382. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48383. break;
  48384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48385. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48386. break;
  48387. }
  48388. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48389. rigCam._cameraRigParams = {};
  48390. return rigCam;
  48391. };
  48392. /**
  48393. * @hidden
  48394. * @override
  48395. * Override Camera._updateRigCameras
  48396. */
  48397. ArcRotateCamera.prototype._updateRigCameras = function () {
  48398. var camLeft = this._rigCameras[0];
  48399. var camRight = this._rigCameras[1];
  48400. camLeft.beta = camRight.beta = this.beta;
  48401. camLeft.radius = camRight.radius = this.radius;
  48402. switch (this.cameraRigMode) {
  48403. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48404. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48405. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48406. case BABYLON.Camera.RIG_MODE_VR:
  48407. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48408. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48409. break;
  48410. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48411. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48412. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48413. break;
  48414. }
  48415. _super.prototype._updateRigCameras.call(this);
  48416. };
  48417. ArcRotateCamera.prototype.dispose = function () {
  48418. this.inputs.clear();
  48419. _super.prototype.dispose.call(this);
  48420. };
  48421. ArcRotateCamera.prototype.getClassName = function () {
  48422. return "ArcRotateCamera";
  48423. };
  48424. __decorate([
  48425. BABYLON.serialize()
  48426. ], ArcRotateCamera.prototype, "alpha", void 0);
  48427. __decorate([
  48428. BABYLON.serialize()
  48429. ], ArcRotateCamera.prototype, "beta", void 0);
  48430. __decorate([
  48431. BABYLON.serialize()
  48432. ], ArcRotateCamera.prototype, "radius", void 0);
  48433. __decorate([
  48434. BABYLON.serializeAsVector3("target")
  48435. ], ArcRotateCamera.prototype, "_target", void 0);
  48436. __decorate([
  48437. BABYLON.serialize()
  48438. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48439. __decorate([
  48440. BABYLON.serialize()
  48441. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48442. __decorate([
  48443. BABYLON.serialize()
  48444. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48445. __decorate([
  48446. BABYLON.serialize()
  48447. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48448. __decorate([
  48449. BABYLON.serialize()
  48450. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48451. __decorate([
  48452. BABYLON.serialize()
  48453. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48454. __decorate([
  48455. BABYLON.serialize()
  48456. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48457. __decorate([
  48458. BABYLON.serialize()
  48459. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48460. __decorate([
  48461. BABYLON.serialize()
  48462. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48463. __decorate([
  48464. BABYLON.serialize()
  48465. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48466. __decorate([
  48467. BABYLON.serialize()
  48468. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48469. __decorate([
  48470. BABYLON.serialize()
  48471. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48472. __decorate([
  48473. BABYLON.serialize()
  48474. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48475. __decorate([
  48476. BABYLON.serializeAsVector3()
  48477. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48478. __decorate([
  48479. BABYLON.serialize()
  48480. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48481. __decorate([
  48482. BABYLON.serialize()
  48483. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48484. __decorate([
  48485. BABYLON.serialize()
  48486. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48487. return ArcRotateCamera;
  48488. }(BABYLON.TargetCamera));
  48489. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48490. })(BABYLON || (BABYLON = {}));
  48491. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48492. var BABYLON;
  48493. (function (BABYLON) {
  48494. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48495. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48496. });
  48497. /**
  48498. * The HemisphericLight simulates the ambient environment light,
  48499. * so the passed direction is the light reflection direction, not the incoming direction.
  48500. */
  48501. var HemisphericLight = /** @class */ (function (_super) {
  48502. __extends(HemisphericLight, _super);
  48503. /**
  48504. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48505. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48506. * The HemisphericLight can't cast shadows.
  48507. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48508. * @param name The friendly name of the light
  48509. * @param direction The direction of the light reflection
  48510. * @param scene The scene the light belongs to
  48511. */
  48512. function HemisphericLight(name, direction, scene) {
  48513. var _this = _super.call(this, name, scene) || this;
  48514. /**
  48515. * The groundColor is the light in the opposite direction to the one specified during creation.
  48516. * 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.
  48517. */
  48518. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48519. _this.direction = direction || BABYLON.Vector3.Up();
  48520. return _this;
  48521. }
  48522. HemisphericLight.prototype._buildUniformLayout = function () {
  48523. this._uniformBuffer.addUniform("vLightData", 4);
  48524. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48525. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48526. this._uniformBuffer.addUniform("vLightGround", 3);
  48527. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48528. this._uniformBuffer.addUniform("depthValues", 2);
  48529. this._uniformBuffer.create();
  48530. };
  48531. /**
  48532. * Returns the string "HemisphericLight".
  48533. * @return The class name
  48534. */
  48535. HemisphericLight.prototype.getClassName = function () {
  48536. return "HemisphericLight";
  48537. };
  48538. /**
  48539. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48540. * Returns the updated direction.
  48541. * @param target The target the direction should point to
  48542. * @return The computed direction
  48543. */
  48544. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48545. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48546. return this.direction;
  48547. };
  48548. /**
  48549. * Returns the shadow generator associated to the light.
  48550. * @returns Always null for hemispheric lights because it does not support shadows.
  48551. */
  48552. HemisphericLight.prototype.getShadowGenerator = function () {
  48553. return null;
  48554. };
  48555. /**
  48556. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48557. * @param effect The effect to update
  48558. * @param lightIndex The index of the light in the effect to update
  48559. * @returns The hemispheric light
  48560. */
  48561. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48562. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48563. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48564. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48565. return this;
  48566. };
  48567. /**
  48568. * @hidden internal use only.
  48569. */
  48570. HemisphericLight.prototype._getWorldMatrix = function () {
  48571. if (!this._worldMatrix) {
  48572. this._worldMatrix = BABYLON.Matrix.Identity();
  48573. }
  48574. return this._worldMatrix;
  48575. };
  48576. /**
  48577. * Returns the integer 3.
  48578. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48579. */
  48580. HemisphericLight.prototype.getTypeID = function () {
  48581. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48582. };
  48583. /**
  48584. * Prepares the list of defines specific to the light type.
  48585. * @param defines the list of defines
  48586. * @param lightIndex defines the index of the light for the effect
  48587. */
  48588. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48589. defines["HEMILIGHT" + lightIndex] = true;
  48590. };
  48591. __decorate([
  48592. BABYLON.serializeAsColor3()
  48593. ], HemisphericLight.prototype, "groundColor", void 0);
  48594. __decorate([
  48595. BABYLON.serializeAsVector3()
  48596. ], HemisphericLight.prototype, "direction", void 0);
  48597. return HemisphericLight;
  48598. }(BABYLON.Light));
  48599. BABYLON.HemisphericLight = HemisphericLight;
  48600. })(BABYLON || (BABYLON = {}));
  48601. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48602. var BABYLON;
  48603. (function (BABYLON) {
  48604. /**
  48605. * Base implementation IShadowLight
  48606. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48607. */
  48608. var ShadowLight = /** @class */ (function (_super) {
  48609. __extends(ShadowLight, _super);
  48610. function ShadowLight() {
  48611. var _this = _super !== null && _super.apply(this, arguments) || this;
  48612. _this._needProjectionMatrixCompute = true;
  48613. return _this;
  48614. }
  48615. ShadowLight.prototype._setPosition = function (value) {
  48616. this._position = value;
  48617. };
  48618. Object.defineProperty(ShadowLight.prototype, "position", {
  48619. /**
  48620. * Sets the position the shadow will be casted from. Also use as the light position for both
  48621. * point and spot lights.
  48622. */
  48623. get: function () {
  48624. return this._position;
  48625. },
  48626. /**
  48627. * Sets the position the shadow will be casted from. Also use as the light position for both
  48628. * point and spot lights.
  48629. */
  48630. set: function (value) {
  48631. this._setPosition(value);
  48632. },
  48633. enumerable: true,
  48634. configurable: true
  48635. });
  48636. ShadowLight.prototype._setDirection = function (value) {
  48637. this._direction = value;
  48638. };
  48639. Object.defineProperty(ShadowLight.prototype, "direction", {
  48640. /**
  48641. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48642. * Also use as the light direction on spot and directional lights.
  48643. */
  48644. get: function () {
  48645. return this._direction;
  48646. },
  48647. /**
  48648. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48649. * Also use as the light direction on spot and directional lights.
  48650. */
  48651. set: function (value) {
  48652. this._setDirection(value);
  48653. },
  48654. enumerable: true,
  48655. configurable: true
  48656. });
  48657. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48658. /**
  48659. * Gets the shadow projection clipping minimum z value.
  48660. */
  48661. get: function () {
  48662. return this._shadowMinZ;
  48663. },
  48664. /**
  48665. * Sets the shadow projection clipping minimum z value.
  48666. */
  48667. set: function (value) {
  48668. this._shadowMinZ = value;
  48669. this.forceProjectionMatrixCompute();
  48670. },
  48671. enumerable: true,
  48672. configurable: true
  48673. });
  48674. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48675. /**
  48676. * Sets the shadow projection clipping maximum z value.
  48677. */
  48678. get: function () {
  48679. return this._shadowMaxZ;
  48680. },
  48681. /**
  48682. * Gets the shadow projection clipping maximum z value.
  48683. */
  48684. set: function (value) {
  48685. this._shadowMaxZ = value;
  48686. this.forceProjectionMatrixCompute();
  48687. },
  48688. enumerable: true,
  48689. configurable: true
  48690. });
  48691. /**
  48692. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48693. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48694. */
  48695. ShadowLight.prototype.computeTransformedInformation = function () {
  48696. if (this.parent && this.parent.getWorldMatrix) {
  48697. if (!this.transformedPosition) {
  48698. this.transformedPosition = BABYLON.Vector3.Zero();
  48699. }
  48700. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48701. // In case the direction is present.
  48702. if (this.direction) {
  48703. if (!this.transformedDirection) {
  48704. this.transformedDirection = BABYLON.Vector3.Zero();
  48705. }
  48706. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48707. }
  48708. return true;
  48709. }
  48710. return false;
  48711. };
  48712. /**
  48713. * Return the depth scale used for the shadow map.
  48714. * @returns the depth scale.
  48715. */
  48716. ShadowLight.prototype.getDepthScale = function () {
  48717. return 50.0;
  48718. };
  48719. /**
  48720. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48721. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48722. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48723. */
  48724. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48725. return this.transformedDirection ? this.transformedDirection : this.direction;
  48726. };
  48727. /**
  48728. * Returns the ShadowLight absolute position in the World.
  48729. * @returns the position vector in world space
  48730. */
  48731. ShadowLight.prototype.getAbsolutePosition = function () {
  48732. return this.transformedPosition ? this.transformedPosition : this.position;
  48733. };
  48734. /**
  48735. * Sets the ShadowLight direction toward the passed target.
  48736. * @param target The point tot target in local space
  48737. * @returns the updated ShadowLight direction
  48738. */
  48739. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48740. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48741. return this.direction;
  48742. };
  48743. /**
  48744. * Returns the light rotation in euler definition.
  48745. * @returns the x y z rotation in local space.
  48746. */
  48747. ShadowLight.prototype.getRotation = function () {
  48748. this.direction.normalize();
  48749. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48750. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48751. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48752. };
  48753. /**
  48754. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48755. * @returns true if a cube texture needs to be use
  48756. */
  48757. ShadowLight.prototype.needCube = function () {
  48758. return false;
  48759. };
  48760. /**
  48761. * Detects if the projection matrix requires to be recomputed this frame.
  48762. * @returns true if it requires to be recomputed otherwise, false.
  48763. */
  48764. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48765. return this._needProjectionMatrixCompute;
  48766. };
  48767. /**
  48768. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48769. */
  48770. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48771. this._needProjectionMatrixCompute = true;
  48772. };
  48773. /**
  48774. * Get the world matrix of the sahdow lights.
  48775. * @hidden Internal Use Only
  48776. */
  48777. ShadowLight.prototype._getWorldMatrix = function () {
  48778. if (!this._worldMatrix) {
  48779. this._worldMatrix = BABYLON.Matrix.Identity();
  48780. }
  48781. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48782. return this._worldMatrix;
  48783. };
  48784. /**
  48785. * Gets the minZ used for shadow according to both the scene and the light.
  48786. * @param activeCamera The camera we are returning the min for
  48787. * @returns the depth min z
  48788. */
  48789. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48790. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48791. };
  48792. /**
  48793. * Gets the maxZ used for shadow according to both the scene and the light.
  48794. * @param activeCamera The camera we are returning the max for
  48795. * @returns the depth max z
  48796. */
  48797. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48798. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48799. };
  48800. /**
  48801. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48802. * @param matrix The materix to updated with the projection information
  48803. * @param viewMatrix The transform matrix of the light
  48804. * @param renderList The list of mesh to render in the map
  48805. * @returns The current light
  48806. */
  48807. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48808. if (this.customProjectionMatrixBuilder) {
  48809. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48810. }
  48811. else {
  48812. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48813. }
  48814. return this;
  48815. };
  48816. __decorate([
  48817. BABYLON.serializeAsVector3()
  48818. ], ShadowLight.prototype, "position", null);
  48819. __decorate([
  48820. BABYLON.serializeAsVector3()
  48821. ], ShadowLight.prototype, "direction", null);
  48822. __decorate([
  48823. BABYLON.serialize()
  48824. ], ShadowLight.prototype, "shadowMinZ", null);
  48825. __decorate([
  48826. BABYLON.serialize()
  48827. ], ShadowLight.prototype, "shadowMaxZ", null);
  48828. return ShadowLight;
  48829. }(BABYLON.Light));
  48830. BABYLON.ShadowLight = ShadowLight;
  48831. })(BABYLON || (BABYLON = {}));
  48832. //# sourceMappingURL=babylon.shadowLight.js.map
  48833. var BABYLON;
  48834. (function (BABYLON) {
  48835. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48836. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48837. });
  48838. /**
  48839. * A point light is a light defined by an unique point in world space.
  48840. * The light is emitted in every direction from this point.
  48841. * A good example of a point light is a standard light bulb.
  48842. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48843. */
  48844. var PointLight = /** @class */ (function (_super) {
  48845. __extends(PointLight, _super);
  48846. /**
  48847. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48848. * A PointLight emits the light in every direction.
  48849. * It can cast shadows.
  48850. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48851. * ```javascript
  48852. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48853. * ```
  48854. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48855. * @param name The light friendly name
  48856. * @param position The position of the point light in the scene
  48857. * @param scene The scene the lights belongs to
  48858. */
  48859. function PointLight(name, position, scene) {
  48860. var _this = _super.call(this, name, scene) || this;
  48861. _this._shadowAngle = Math.PI / 2;
  48862. _this.position = position;
  48863. return _this;
  48864. }
  48865. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48866. /**
  48867. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48868. * This specifies what angle the shadow will use to be created.
  48869. *
  48870. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48871. */
  48872. get: function () {
  48873. return this._shadowAngle;
  48874. },
  48875. /**
  48876. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48877. * This specifies what angle the shadow will use to be created.
  48878. *
  48879. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48880. */
  48881. set: function (value) {
  48882. this._shadowAngle = value;
  48883. this.forceProjectionMatrixCompute();
  48884. },
  48885. enumerable: true,
  48886. configurable: true
  48887. });
  48888. Object.defineProperty(PointLight.prototype, "direction", {
  48889. /**
  48890. * Gets the direction if it has been set.
  48891. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48892. */
  48893. get: function () {
  48894. return this._direction;
  48895. },
  48896. /**
  48897. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48898. */
  48899. set: function (value) {
  48900. var previousNeedCube = this.needCube();
  48901. this._direction = value;
  48902. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48903. this._shadowGenerator.recreateShadowMap();
  48904. }
  48905. },
  48906. enumerable: true,
  48907. configurable: true
  48908. });
  48909. /**
  48910. * Returns the string "PointLight"
  48911. * @returns the class name
  48912. */
  48913. PointLight.prototype.getClassName = function () {
  48914. return "PointLight";
  48915. };
  48916. /**
  48917. * Returns the integer 0.
  48918. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48919. */
  48920. PointLight.prototype.getTypeID = function () {
  48921. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48922. };
  48923. /**
  48924. * Specifies wether or not the shadowmap should be a cube texture.
  48925. * @returns true if the shadowmap needs to be a cube texture.
  48926. */
  48927. PointLight.prototype.needCube = function () {
  48928. return !this.direction;
  48929. };
  48930. /**
  48931. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48932. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48933. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48934. */
  48935. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48936. if (this.direction) {
  48937. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48938. }
  48939. else {
  48940. switch (faceIndex) {
  48941. case 0:
  48942. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48943. case 1:
  48944. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48945. case 2:
  48946. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48947. case 3:
  48948. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48949. case 4:
  48950. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48951. case 5:
  48952. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48953. }
  48954. }
  48955. return BABYLON.Vector3.Zero();
  48956. };
  48957. /**
  48958. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48959. * - fov = PI / 2
  48960. * - aspect ratio : 1.0
  48961. * - z-near and far equal to the active camera minZ and maxZ.
  48962. * Returns the PointLight.
  48963. */
  48964. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48965. var activeCamera = this.getScene().activeCamera;
  48966. if (!activeCamera) {
  48967. return;
  48968. }
  48969. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48970. };
  48971. PointLight.prototype._buildUniformLayout = function () {
  48972. this._uniformBuffer.addUniform("vLightData", 4);
  48973. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48974. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48975. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48976. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48977. this._uniformBuffer.addUniform("depthValues", 2);
  48978. this._uniformBuffer.create();
  48979. };
  48980. /**
  48981. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48982. * @param effect The effect to update
  48983. * @param lightIndex The index of the light in the effect to update
  48984. * @returns The point light
  48985. */
  48986. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48987. if (this.computeTransformedInformation()) {
  48988. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48989. }
  48990. else {
  48991. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48992. }
  48993. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48994. return this;
  48995. };
  48996. /**
  48997. * Prepares the list of defines specific to the light type.
  48998. * @param defines the list of defines
  48999. * @param lightIndex defines the index of the light for the effect
  49000. */
  49001. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49002. defines["POINTLIGHT" + lightIndex] = true;
  49003. };
  49004. __decorate([
  49005. BABYLON.serialize()
  49006. ], PointLight.prototype, "shadowAngle", null);
  49007. return PointLight;
  49008. }(BABYLON.ShadowLight));
  49009. BABYLON.PointLight = PointLight;
  49010. })(BABYLON || (BABYLON = {}));
  49011. //# sourceMappingURL=babylon.pointLight.js.map
  49012. var BABYLON;
  49013. (function (BABYLON) {
  49014. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49015. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49016. });
  49017. /**
  49018. * A directional light is defined by a direction (what a surprise!).
  49019. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49020. * 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.
  49021. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49022. */
  49023. var DirectionalLight = /** @class */ (function (_super) {
  49024. __extends(DirectionalLight, _super);
  49025. /**
  49026. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49027. * The directional light is emitted from everywhere in the given direction.
  49028. * It can cast shawdows.
  49029. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49030. * @param name The friendly name of the light
  49031. * @param direction The direction of the light
  49032. * @param scene The scene the light belongs to
  49033. */
  49034. function DirectionalLight(name, direction, scene) {
  49035. var _this = _super.call(this, name, scene) || this;
  49036. _this._shadowFrustumSize = 0;
  49037. _this._shadowOrthoScale = 0.1;
  49038. /**
  49039. * Automatically compute the projection matrix to best fit (including all the casters)
  49040. * on each frame.
  49041. */
  49042. _this.autoUpdateExtends = true;
  49043. // Cache
  49044. _this._orthoLeft = Number.MAX_VALUE;
  49045. _this._orthoRight = Number.MIN_VALUE;
  49046. _this._orthoTop = Number.MIN_VALUE;
  49047. _this._orthoBottom = Number.MAX_VALUE;
  49048. _this.position = direction.scale(-1.0);
  49049. _this.direction = direction;
  49050. return _this;
  49051. }
  49052. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49053. /**
  49054. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49055. */
  49056. get: function () {
  49057. return this._shadowFrustumSize;
  49058. },
  49059. /**
  49060. * Specifies a fix frustum size for the shadow generation.
  49061. */
  49062. set: function (value) {
  49063. this._shadowFrustumSize = value;
  49064. this.forceProjectionMatrixCompute();
  49065. },
  49066. enumerable: true,
  49067. configurable: true
  49068. });
  49069. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49070. /**
  49071. * Gets the shadow projection scale against the optimal computed one.
  49072. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49073. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49074. */
  49075. get: function () {
  49076. return this._shadowOrthoScale;
  49077. },
  49078. /**
  49079. * Sets the shadow projection scale against the optimal computed one.
  49080. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49081. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49082. */
  49083. set: function (value) {
  49084. this._shadowOrthoScale = value;
  49085. this.forceProjectionMatrixCompute();
  49086. },
  49087. enumerable: true,
  49088. configurable: true
  49089. });
  49090. /**
  49091. * Returns the string "DirectionalLight".
  49092. * @return The class name
  49093. */
  49094. DirectionalLight.prototype.getClassName = function () {
  49095. return "DirectionalLight";
  49096. };
  49097. /**
  49098. * Returns the integer 1.
  49099. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49100. */
  49101. DirectionalLight.prototype.getTypeID = function () {
  49102. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49103. };
  49104. /**
  49105. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49106. * Returns the DirectionalLight Shadow projection matrix.
  49107. */
  49108. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49109. if (this.shadowFrustumSize > 0) {
  49110. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49111. }
  49112. else {
  49113. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49114. }
  49115. };
  49116. /**
  49117. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49118. * Returns the DirectionalLight Shadow projection matrix.
  49119. */
  49120. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49121. var activeCamera = this.getScene().activeCamera;
  49122. if (!activeCamera) {
  49123. return;
  49124. }
  49125. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49126. };
  49127. /**
  49128. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49129. * Returns the DirectionalLight Shadow projection matrix.
  49130. */
  49131. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49132. var activeCamera = this.getScene().activeCamera;
  49133. if (!activeCamera) {
  49134. return;
  49135. }
  49136. // Check extends
  49137. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49138. var tempVector3 = BABYLON.Vector3.Zero();
  49139. this._orthoLeft = Number.MAX_VALUE;
  49140. this._orthoRight = Number.MIN_VALUE;
  49141. this._orthoTop = Number.MIN_VALUE;
  49142. this._orthoBottom = Number.MAX_VALUE;
  49143. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49144. var mesh = renderList[meshIndex];
  49145. if (!mesh) {
  49146. continue;
  49147. }
  49148. var boundingInfo = mesh.getBoundingInfo();
  49149. var boundingBox = boundingInfo.boundingBox;
  49150. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49151. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49152. if (tempVector3.x < this._orthoLeft)
  49153. this._orthoLeft = tempVector3.x;
  49154. if (tempVector3.y < this._orthoBottom)
  49155. this._orthoBottom = tempVector3.y;
  49156. if (tempVector3.x > this._orthoRight)
  49157. this._orthoRight = tempVector3.x;
  49158. if (tempVector3.y > this._orthoTop)
  49159. this._orthoTop = tempVector3.y;
  49160. }
  49161. }
  49162. }
  49163. var xOffset = this._orthoRight - this._orthoLeft;
  49164. var yOffset = this._orthoTop - this._orthoBottom;
  49165. 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);
  49166. };
  49167. DirectionalLight.prototype._buildUniformLayout = function () {
  49168. this._uniformBuffer.addUniform("vLightData", 4);
  49169. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49170. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49171. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49172. this._uniformBuffer.addUniform("depthValues", 2);
  49173. this._uniformBuffer.create();
  49174. };
  49175. /**
  49176. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49177. * @param effect The effect to update
  49178. * @param lightIndex The index of the light in the effect to update
  49179. * @returns The directional light
  49180. */
  49181. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49182. if (this.computeTransformedInformation()) {
  49183. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49184. return this;
  49185. }
  49186. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49187. return this;
  49188. };
  49189. /**
  49190. * Gets the minZ used for shadow according to both the scene and the light.
  49191. *
  49192. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49193. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49194. * @param activeCamera The camera we are returning the min for
  49195. * @returns the depth min z
  49196. */
  49197. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49198. return 1;
  49199. };
  49200. /**
  49201. * Gets the maxZ used for shadow according to both the scene and the light.
  49202. *
  49203. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49204. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49205. * @param activeCamera The camera we are returning the max for
  49206. * @returns the depth max z
  49207. */
  49208. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49209. return 1;
  49210. };
  49211. /**
  49212. * Prepares the list of defines specific to the light type.
  49213. * @param defines the list of defines
  49214. * @param lightIndex defines the index of the light for the effect
  49215. */
  49216. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49217. defines["DIRLIGHT" + lightIndex] = true;
  49218. };
  49219. __decorate([
  49220. BABYLON.serialize()
  49221. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49222. __decorate([
  49223. BABYLON.serialize()
  49224. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49225. __decorate([
  49226. BABYLON.serialize()
  49227. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49228. return DirectionalLight;
  49229. }(BABYLON.ShadowLight));
  49230. BABYLON.DirectionalLight = DirectionalLight;
  49231. })(BABYLON || (BABYLON = {}));
  49232. //# sourceMappingURL=babylon.directionalLight.js.map
  49233. var BABYLON;
  49234. (function (BABYLON) {
  49235. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49236. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49237. });
  49238. /**
  49239. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49240. * These values define a cone of light starting from the position, emitting toward the direction.
  49241. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49242. * and the exponent defines the speed of the decay of the light with distance (reach).
  49243. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49244. */
  49245. var SpotLight = /** @class */ (function (_super) {
  49246. __extends(SpotLight, _super);
  49247. /**
  49248. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49249. * It can cast shadows.
  49250. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49251. * @param name The light friendly name
  49252. * @param position The position of the spot light in the scene
  49253. * @param direction The direction of the light in the scene
  49254. * @param angle The cone angle of the light in Radians
  49255. * @param exponent The light decay speed with the distance from the emission spot
  49256. * @param scene The scene the lights belongs to
  49257. */
  49258. function SpotLight(name, position, direction, angle, exponent, scene) {
  49259. var _this = _super.call(this, name, scene) || this;
  49260. _this._innerAngle = 0;
  49261. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49262. _this._projectionTextureLightNear = 1e-6;
  49263. _this._projectionTextureLightFar = 1000.0;
  49264. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49265. _this._projectionTextureViewLightDirty = true;
  49266. _this._projectionTextureProjectionLightDirty = true;
  49267. _this._projectionTextureDirty = true;
  49268. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49269. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49270. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49271. _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);
  49272. _this.position = position;
  49273. _this.direction = direction;
  49274. _this.angle = angle;
  49275. _this.exponent = exponent;
  49276. return _this;
  49277. }
  49278. Object.defineProperty(SpotLight.prototype, "angle", {
  49279. /**
  49280. * Gets the cone angle of the spot light in Radians.
  49281. */
  49282. get: function () {
  49283. return this._angle;
  49284. },
  49285. /**
  49286. * Sets the cone angle of the spot light in Radians.
  49287. */
  49288. set: function (value) {
  49289. this._angle = value;
  49290. this._cosHalfAngle = Math.cos(value * 0.5);
  49291. this._projectionTextureProjectionLightDirty = true;
  49292. this.forceProjectionMatrixCompute();
  49293. this._computeAngleValues();
  49294. },
  49295. enumerable: true,
  49296. configurable: true
  49297. });
  49298. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49299. /**
  49300. * Only used in gltf falloff mode, this defines the angle where
  49301. * the directional falloff will start before cutting at angle which could be seen
  49302. * as outer angle.
  49303. */
  49304. get: function () {
  49305. return this._angle;
  49306. },
  49307. /**
  49308. * Only used in gltf falloff mode, this defines the angle where
  49309. * the directional falloff will start before cutting at angle which could be seen
  49310. * as outer angle.
  49311. */
  49312. set: function (value) {
  49313. this._innerAngle = value;
  49314. this._computeAngleValues();
  49315. },
  49316. enumerable: true,
  49317. configurable: true
  49318. });
  49319. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49320. /**
  49321. * Allows scaling the angle of the light for shadow generation only.
  49322. */
  49323. get: function () {
  49324. return this._shadowAngleScale;
  49325. },
  49326. /**
  49327. * Allows scaling the angle of the light for shadow generation only.
  49328. */
  49329. set: function (value) {
  49330. this._shadowAngleScale = value;
  49331. this.forceProjectionMatrixCompute();
  49332. },
  49333. enumerable: true,
  49334. configurable: true
  49335. });
  49336. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49337. /**
  49338. * Allows reading the projecton texture
  49339. */
  49340. get: function () {
  49341. return this._projectionTextureMatrix;
  49342. },
  49343. enumerable: true,
  49344. configurable: true
  49345. });
  49346. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49347. /**
  49348. * Gets the near clip of the Spotlight for texture projection.
  49349. */
  49350. get: function () {
  49351. return this._projectionTextureLightNear;
  49352. },
  49353. /**
  49354. * Sets the near clip of the Spotlight for texture projection.
  49355. */
  49356. set: function (value) {
  49357. this._projectionTextureLightNear = value;
  49358. this._projectionTextureProjectionLightDirty = true;
  49359. },
  49360. enumerable: true,
  49361. configurable: true
  49362. });
  49363. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49364. /**
  49365. * Gets the far clip of the Spotlight for texture projection.
  49366. */
  49367. get: function () {
  49368. return this._projectionTextureLightFar;
  49369. },
  49370. /**
  49371. * Sets the far clip of the Spotlight for texture projection.
  49372. */
  49373. set: function (value) {
  49374. this._projectionTextureLightFar = value;
  49375. this._projectionTextureProjectionLightDirty = true;
  49376. },
  49377. enumerable: true,
  49378. configurable: true
  49379. });
  49380. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49381. /**
  49382. * Gets the Up vector of the Spotlight for texture projection.
  49383. */
  49384. get: function () {
  49385. return this._projectionTextureUpDirection;
  49386. },
  49387. /**
  49388. * Sets the Up vector of the Spotlight for texture projection.
  49389. */
  49390. set: function (value) {
  49391. this._projectionTextureUpDirection = value;
  49392. this._projectionTextureProjectionLightDirty = true;
  49393. },
  49394. enumerable: true,
  49395. configurable: true
  49396. });
  49397. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49398. /**
  49399. * Gets the projection texture of the light.
  49400. */
  49401. get: function () {
  49402. return this._projectionTexture;
  49403. },
  49404. /**
  49405. * Sets the projection texture of the light.
  49406. */
  49407. set: function (value) {
  49408. this._projectionTexture = value;
  49409. this._projectionTextureDirty = true;
  49410. },
  49411. enumerable: true,
  49412. configurable: true
  49413. });
  49414. /**
  49415. * Returns the string "SpotLight".
  49416. * @returns the class name
  49417. */
  49418. SpotLight.prototype.getClassName = function () {
  49419. return "SpotLight";
  49420. };
  49421. /**
  49422. * Returns the integer 2.
  49423. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49424. */
  49425. SpotLight.prototype.getTypeID = function () {
  49426. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49427. };
  49428. /**
  49429. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49430. */
  49431. SpotLight.prototype._setDirection = function (value) {
  49432. _super.prototype._setDirection.call(this, value);
  49433. this._projectionTextureViewLightDirty = true;
  49434. };
  49435. /**
  49436. * Overrides the position setter to recompute the projection texture view light Matrix.
  49437. */
  49438. SpotLight.prototype._setPosition = function (value) {
  49439. _super.prototype._setPosition.call(this, value);
  49440. this._projectionTextureViewLightDirty = true;
  49441. };
  49442. /**
  49443. * 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.
  49444. * Returns the SpotLight.
  49445. */
  49446. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49447. var activeCamera = this.getScene().activeCamera;
  49448. if (!activeCamera) {
  49449. return;
  49450. }
  49451. this._shadowAngleScale = this._shadowAngleScale || 1;
  49452. var angle = this._shadowAngleScale * this._angle;
  49453. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49454. };
  49455. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49456. this._projectionTextureViewLightDirty = false;
  49457. this._projectionTextureDirty = true;
  49458. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49459. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49460. };
  49461. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49462. this._projectionTextureProjectionLightDirty = false;
  49463. this._projectionTextureDirty = true;
  49464. var light_far = this.projectionTextureLightFar;
  49465. var light_near = this.projectionTextureLightNear;
  49466. var P = light_far / (light_far - light_near);
  49467. var Q = -P * light_near;
  49468. var S = 1.0 / Math.tan(this._angle / 2.0);
  49469. var A = 1.0;
  49470. 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);
  49471. };
  49472. /**
  49473. * Main function for light texture projection matrix computing.
  49474. */
  49475. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49476. this._projectionTextureDirty = false;
  49477. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49478. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49479. };
  49480. SpotLight.prototype._buildUniformLayout = function () {
  49481. this._uniformBuffer.addUniform("vLightData", 4);
  49482. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49483. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49484. this._uniformBuffer.addUniform("vLightDirection", 3);
  49485. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49486. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49487. this._uniformBuffer.addUniform("depthValues", 2);
  49488. this._uniformBuffer.create();
  49489. };
  49490. SpotLight.prototype._computeAngleValues = function () {
  49491. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49492. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49493. };
  49494. /**
  49495. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49496. * @param effect The effect to update
  49497. * @param lightIndex The index of the light in the effect to update
  49498. * @returns The spot light
  49499. */
  49500. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49501. var normalizeDirection;
  49502. if (this.computeTransformedInformation()) {
  49503. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49504. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49505. }
  49506. else {
  49507. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49508. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49509. }
  49510. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49511. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49512. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49513. if (this._projectionTextureViewLightDirty) {
  49514. this._computeProjectionTextureViewLightMatrix();
  49515. }
  49516. if (this._projectionTextureProjectionLightDirty) {
  49517. this._computeProjectionTextureProjectionLightMatrix();
  49518. }
  49519. if (this._projectionTextureDirty) {
  49520. this._computeProjectionTextureMatrix();
  49521. }
  49522. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49523. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49524. }
  49525. return this;
  49526. };
  49527. /**
  49528. * Disposes the light and the associated resources.
  49529. */
  49530. SpotLight.prototype.dispose = function () {
  49531. _super.prototype.dispose.call(this);
  49532. if (this._projectionTexture) {
  49533. this._projectionTexture.dispose();
  49534. }
  49535. };
  49536. /**
  49537. * Prepares the list of defines specific to the light type.
  49538. * @param defines the list of defines
  49539. * @param lightIndex defines the index of the light for the effect
  49540. */
  49541. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49542. defines["SPOTLIGHT" + lightIndex] = true;
  49543. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49544. };
  49545. __decorate([
  49546. BABYLON.serialize()
  49547. ], SpotLight.prototype, "angle", null);
  49548. __decorate([
  49549. BABYLON.serialize()
  49550. ], SpotLight.prototype, "innerAngle", null);
  49551. __decorate([
  49552. BABYLON.serialize()
  49553. ], SpotLight.prototype, "shadowAngleScale", null);
  49554. __decorate([
  49555. BABYLON.serialize()
  49556. ], SpotLight.prototype, "exponent", void 0);
  49557. __decorate([
  49558. BABYLON.serialize()
  49559. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49560. __decorate([
  49561. BABYLON.serialize()
  49562. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49563. __decorate([
  49564. BABYLON.serialize()
  49565. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49566. __decorate([
  49567. BABYLON.serializeAsTexture("projectedLightTexture")
  49568. ], SpotLight.prototype, "_projectionTexture", void 0);
  49569. return SpotLight;
  49570. }(BABYLON.ShadowLight));
  49571. BABYLON.SpotLight = SpotLight;
  49572. })(BABYLON || (BABYLON = {}));
  49573. //# sourceMappingURL=babylon.spotLight.js.map
  49574. var BABYLON;
  49575. (function (BABYLON) {
  49576. /**
  49577. * Class used to override all child animations of a given target
  49578. */
  49579. var AnimationPropertiesOverride = /** @class */ (function () {
  49580. function AnimationPropertiesOverride() {
  49581. /**
  49582. * Gets or sets a value indicating if animation blending must be used
  49583. */
  49584. this.enableBlending = false;
  49585. /**
  49586. * Gets or sets the blending speed to use when enableBlending is true
  49587. */
  49588. this.blendingSpeed = 0.01;
  49589. /**
  49590. * Gets or sets the default loop mode to use
  49591. */
  49592. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49593. }
  49594. return AnimationPropertiesOverride;
  49595. }());
  49596. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49597. })(BABYLON || (BABYLON = {}));
  49598. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49599. var BABYLON;
  49600. (function (BABYLON) {
  49601. /**
  49602. * Represents the range of an animation
  49603. */
  49604. var AnimationRange = /** @class */ (function () {
  49605. /**
  49606. * Initializes the range of an animation
  49607. * @param name The name of the animation range
  49608. * @param from The starting frame of the animation
  49609. * @param to The ending frame of the animation
  49610. */
  49611. function AnimationRange(
  49612. /**The name of the animation range**/
  49613. name,
  49614. /**The starting frame of the animation */
  49615. from,
  49616. /**The ending frame of the animation*/
  49617. to) {
  49618. this.name = name;
  49619. this.from = from;
  49620. this.to = to;
  49621. }
  49622. /**
  49623. * Makes a copy of the animation range
  49624. * @returns A copy of the animation range
  49625. */
  49626. AnimationRange.prototype.clone = function () {
  49627. return new AnimationRange(this.name, this.from, this.to);
  49628. };
  49629. return AnimationRange;
  49630. }());
  49631. BABYLON.AnimationRange = AnimationRange;
  49632. /**
  49633. * Composed of a frame, and an action function
  49634. */
  49635. var AnimationEvent = /** @class */ (function () {
  49636. /**
  49637. * Initializes the animation event
  49638. * @param frame The frame for which the event is triggered
  49639. * @param action The event to perform when triggered
  49640. * @param onlyOnce Specifies if the event should be triggered only once
  49641. */
  49642. function AnimationEvent(
  49643. /** The frame for which the event is triggered **/
  49644. frame,
  49645. /** The event to perform when triggered **/
  49646. action,
  49647. /** Specifies if the event should be triggered only once**/
  49648. onlyOnce) {
  49649. this.frame = frame;
  49650. this.action = action;
  49651. this.onlyOnce = onlyOnce;
  49652. /**
  49653. * Specifies if the animation event is done
  49654. */
  49655. this.isDone = false;
  49656. }
  49657. /** @hidden */
  49658. AnimationEvent.prototype._clone = function () {
  49659. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49660. };
  49661. return AnimationEvent;
  49662. }());
  49663. BABYLON.AnimationEvent = AnimationEvent;
  49664. /**
  49665. * A cursor which tracks a point on a path
  49666. */
  49667. var PathCursor = /** @class */ (function () {
  49668. /**
  49669. * Initializes the path cursor
  49670. * @param path The path to track
  49671. */
  49672. function PathCursor(path) {
  49673. this.path = path;
  49674. /**
  49675. * Stores path cursor callbacks for when an onchange event is triggered
  49676. */
  49677. this._onchange = new Array();
  49678. /**
  49679. * The value of the path cursor
  49680. */
  49681. this.value = 0;
  49682. /**
  49683. * The animation array of the path cursor
  49684. */
  49685. this.animations = new Array();
  49686. }
  49687. /**
  49688. * Gets the cursor point on the path
  49689. * @returns A point on the path cursor at the cursor location
  49690. */
  49691. PathCursor.prototype.getPoint = function () {
  49692. var point = this.path.getPointAtLengthPosition(this.value);
  49693. return new BABYLON.Vector3(point.x, 0, point.y);
  49694. };
  49695. /**
  49696. * Moves the cursor ahead by the step amount
  49697. * @param step The amount to move the cursor forward
  49698. * @returns This path cursor
  49699. */
  49700. PathCursor.prototype.moveAhead = function (step) {
  49701. if (step === void 0) { step = 0.002; }
  49702. this.move(step);
  49703. return this;
  49704. };
  49705. /**
  49706. * Moves the cursor behind by the step amount
  49707. * @param step The amount to move the cursor back
  49708. * @returns This path cursor
  49709. */
  49710. PathCursor.prototype.moveBack = function (step) {
  49711. if (step === void 0) { step = 0.002; }
  49712. this.move(-step);
  49713. return this;
  49714. };
  49715. /**
  49716. * Moves the cursor by the step amount
  49717. * If the step amount is greater than one, an exception is thrown
  49718. * @param step The amount to move the cursor
  49719. * @returns This path cursor
  49720. */
  49721. PathCursor.prototype.move = function (step) {
  49722. if (Math.abs(step) > 1) {
  49723. throw "step size should be less than 1.";
  49724. }
  49725. this.value += step;
  49726. this.ensureLimits();
  49727. this.raiseOnChange();
  49728. return this;
  49729. };
  49730. /**
  49731. * Ensures that the value is limited between zero and one
  49732. * @returns This path cursor
  49733. */
  49734. PathCursor.prototype.ensureLimits = function () {
  49735. while (this.value > 1) {
  49736. this.value -= 1;
  49737. }
  49738. while (this.value < 0) {
  49739. this.value += 1;
  49740. }
  49741. return this;
  49742. };
  49743. /**
  49744. * Runs onchange callbacks on change (used by the animation engine)
  49745. * @returns This path cursor
  49746. */
  49747. PathCursor.prototype.raiseOnChange = function () {
  49748. var _this = this;
  49749. this._onchange.forEach(function (f) { return f(_this); });
  49750. return this;
  49751. };
  49752. /**
  49753. * Executes a function on change
  49754. * @param f A path cursor onchange callback
  49755. * @returns This path cursor
  49756. */
  49757. PathCursor.prototype.onchange = function (f) {
  49758. this._onchange.push(f);
  49759. return this;
  49760. };
  49761. return PathCursor;
  49762. }());
  49763. BABYLON.PathCursor = PathCursor;
  49764. /**
  49765. * Enum for the animation key frame interpolation type
  49766. */
  49767. var AnimationKeyInterpolation;
  49768. (function (AnimationKeyInterpolation) {
  49769. /**
  49770. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49771. */
  49772. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49773. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49774. /**
  49775. * Class used to store any kind of animation
  49776. */
  49777. var Animation = /** @class */ (function () {
  49778. /**
  49779. * Initializes the animation
  49780. * @param name Name of the animation
  49781. * @param targetProperty Property to animate
  49782. * @param framePerSecond The frames per second of the animation
  49783. * @param dataType The data type of the animation
  49784. * @param loopMode The loop mode of the animation
  49785. * @param enableBlendings Specifies if blending should be enabled
  49786. */
  49787. function Animation(
  49788. /**Name of the animation */
  49789. name,
  49790. /**Property to animate */
  49791. targetProperty,
  49792. /**The frames per second of the animation */
  49793. framePerSecond,
  49794. /**The data type of the animation */
  49795. dataType,
  49796. /**The loop mode of the animation */
  49797. loopMode,
  49798. /**Specifies if blending should be enabled */
  49799. enableBlending) {
  49800. this.name = name;
  49801. this.targetProperty = targetProperty;
  49802. this.framePerSecond = framePerSecond;
  49803. this.dataType = dataType;
  49804. this.loopMode = loopMode;
  49805. this.enableBlending = enableBlending;
  49806. /**
  49807. * @hidden Internal use only
  49808. */
  49809. this._runtimeAnimations = new Array();
  49810. /**
  49811. * The set of event that will be linked to this animation
  49812. */
  49813. this._events = new Array();
  49814. /**
  49815. * Stores the blending speed of the animation
  49816. */
  49817. this.blendingSpeed = 0.01;
  49818. /**
  49819. * Stores the animation ranges for the animation
  49820. */
  49821. this._ranges = {};
  49822. this.targetPropertyPath = targetProperty.split(".");
  49823. this.dataType = dataType;
  49824. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49825. }
  49826. /**
  49827. * @hidden Internal use
  49828. */
  49829. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49830. var dataType = undefined;
  49831. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49832. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49833. }
  49834. else if (from instanceof BABYLON.Quaternion) {
  49835. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49836. }
  49837. else if (from instanceof BABYLON.Vector3) {
  49838. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49839. }
  49840. else if (from instanceof BABYLON.Vector2) {
  49841. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49842. }
  49843. else if (from instanceof BABYLON.Color3) {
  49844. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49845. }
  49846. else if (from instanceof BABYLON.Size) {
  49847. dataType = Animation.ANIMATIONTYPE_SIZE;
  49848. }
  49849. if (dataType == undefined) {
  49850. return null;
  49851. }
  49852. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49853. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49854. animation.setKeys(keys);
  49855. if (easingFunction !== undefined) {
  49856. animation.setEasingFunction(easingFunction);
  49857. }
  49858. return animation;
  49859. };
  49860. /**
  49861. * Sets up an animation
  49862. * @param property The property to animate
  49863. * @param animationType The animation type to apply
  49864. * @param framePerSecond The frames per second of the animation
  49865. * @param easingFunction The easing function used in the animation
  49866. * @returns The created animation
  49867. */
  49868. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49869. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49870. animation.setEasingFunction(easingFunction);
  49871. return animation;
  49872. };
  49873. /**
  49874. * Create and start an animation on a node
  49875. * @param name defines the name of the global animation that will be run on all nodes
  49876. * @param node defines the root node where the animation will take place
  49877. * @param targetProperty defines property to animate
  49878. * @param framePerSecond defines the number of frame per second yo use
  49879. * @param totalFrame defines the number of frames in total
  49880. * @param from defines the initial value
  49881. * @param to defines the final value
  49882. * @param loopMode defines which loop mode you want to use (off by default)
  49883. * @param easingFunction defines the easing function to use (linear by default)
  49884. * @param onAnimationEnd defines the callback to call when animation end
  49885. * @returns the animatable created for this animation
  49886. */
  49887. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49888. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49889. if (!animation) {
  49890. return null;
  49891. }
  49892. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49893. };
  49894. /**
  49895. * Create and start an animation on a node and its descendants
  49896. * @param name defines the name of the global animation that will be run on all nodes
  49897. * @param node defines the root node where the animation will take place
  49898. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  49899. * @param targetProperty defines property to animate
  49900. * @param framePerSecond defines the number of frame per second to use
  49901. * @param totalFrame defines the number of frames in total
  49902. * @param from defines the initial value
  49903. * @param to defines the final value
  49904. * @param loopMode defines which loop mode you want to use (off by default)
  49905. * @param easingFunction defines the easing function to use (linear by default)
  49906. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49907. * @returns the list of animatables created for all nodes
  49908. * @example https://www.babylonjs-playground.com/#MH0VLI
  49909. */
  49910. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49911. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49912. if (!animation) {
  49913. return null;
  49914. }
  49915. var scene = node.getScene();
  49916. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49917. };
  49918. /**
  49919. * Creates a new animation, merges it with the existing animations and starts it
  49920. * @param name Name of the animation
  49921. * @param node Node which contains the scene that begins the animations
  49922. * @param targetProperty Specifies which property to animate
  49923. * @param framePerSecond The frames per second of the animation
  49924. * @param totalFrame The total number of frames
  49925. * @param from The frame at the beginning of the animation
  49926. * @param to The frame at the end of the animation
  49927. * @param loopMode Specifies the loop mode of the animation
  49928. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49929. * @param onAnimationEnd Callback to run once the animation is complete
  49930. * @returns Nullable animation
  49931. */
  49932. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49933. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49934. if (!animation) {
  49935. return null;
  49936. }
  49937. node.animations.push(animation);
  49938. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49939. };
  49940. /**
  49941. * Transition property of an host to the target Value
  49942. * @param property The property to transition
  49943. * @param targetValue The target Value of the property
  49944. * @param host The object where the property to animate belongs
  49945. * @param scene Scene used to run the animation
  49946. * @param frameRate Framerate (in frame/s) to use
  49947. * @param transition The transition type we want to use
  49948. * @param duration The duration of the animation, in milliseconds
  49949. * @param onAnimationEnd Callback trigger at the end of the animation
  49950. * @returns Nullable animation
  49951. */
  49952. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49953. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49954. if (duration <= 0) {
  49955. host[property] = targetValue;
  49956. if (onAnimationEnd) {
  49957. onAnimationEnd();
  49958. }
  49959. return null;
  49960. }
  49961. var endFrame = frameRate * (duration / 1000);
  49962. transition.setKeys([{
  49963. frame: 0,
  49964. value: host[property].clone ? host[property].clone() : host[property]
  49965. },
  49966. {
  49967. frame: endFrame,
  49968. value: targetValue
  49969. }]);
  49970. if (!host.animations) {
  49971. host.animations = [];
  49972. }
  49973. host.animations.push(transition);
  49974. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49975. animation.onAnimationEnd = onAnimationEnd;
  49976. return animation;
  49977. };
  49978. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49979. /**
  49980. * Return the array of runtime animations currently using this animation
  49981. */
  49982. get: function () {
  49983. return this._runtimeAnimations;
  49984. },
  49985. enumerable: true,
  49986. configurable: true
  49987. });
  49988. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49989. /**
  49990. * Specifies if any of the runtime animations are currently running
  49991. */
  49992. get: function () {
  49993. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49994. var runtimeAnimation = _a[_i];
  49995. if (!runtimeAnimation.isStopped) {
  49996. return true;
  49997. }
  49998. }
  49999. return false;
  50000. },
  50001. enumerable: true,
  50002. configurable: true
  50003. });
  50004. // Methods
  50005. /**
  50006. * Converts the animation to a string
  50007. * @param fullDetails support for multiple levels of logging within scene loading
  50008. * @returns String form of the animation
  50009. */
  50010. Animation.prototype.toString = function (fullDetails) {
  50011. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50012. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50013. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50014. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50015. if (fullDetails) {
  50016. ret += ", Ranges: {";
  50017. var first = true;
  50018. for (var name in this._ranges) {
  50019. if (first) {
  50020. ret += ", ";
  50021. first = false;
  50022. }
  50023. ret += name;
  50024. }
  50025. ret += "}";
  50026. }
  50027. return ret;
  50028. };
  50029. /**
  50030. * Add an event to this animation
  50031. * @param event Event to add
  50032. */
  50033. Animation.prototype.addEvent = function (event) {
  50034. this._events.push(event);
  50035. };
  50036. /**
  50037. * Remove all events found at the given frame
  50038. * @param frame The frame to remove events from
  50039. */
  50040. Animation.prototype.removeEvents = function (frame) {
  50041. for (var index = 0; index < this._events.length; index++) {
  50042. if (this._events[index].frame === frame) {
  50043. this._events.splice(index, 1);
  50044. index--;
  50045. }
  50046. }
  50047. };
  50048. /**
  50049. * Retrieves all the events from the animation
  50050. * @returns Events from the animation
  50051. */
  50052. Animation.prototype.getEvents = function () {
  50053. return this._events;
  50054. };
  50055. /**
  50056. * Creates an animation range
  50057. * @param name Name of the animation range
  50058. * @param from Starting frame of the animation range
  50059. * @param to Ending frame of the animation
  50060. */
  50061. Animation.prototype.createRange = function (name, from, to) {
  50062. // check name not already in use; could happen for bones after serialized
  50063. if (!this._ranges[name]) {
  50064. this._ranges[name] = new AnimationRange(name, from, to);
  50065. }
  50066. };
  50067. /**
  50068. * Deletes an animation range by name
  50069. * @param name Name of the animation range to delete
  50070. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50071. */
  50072. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50073. if (deleteFrames === void 0) { deleteFrames = true; }
  50074. var range = this._ranges[name];
  50075. if (!range) {
  50076. return;
  50077. }
  50078. if (deleteFrames) {
  50079. var from = range.from;
  50080. var to = range.to;
  50081. // this loop MUST go high to low for multiple splices to work
  50082. for (var key = this._keys.length - 1; key >= 0; key--) {
  50083. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50084. this._keys.splice(key, 1);
  50085. }
  50086. }
  50087. }
  50088. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50089. };
  50090. /**
  50091. * Gets the animation range by name, or null if not defined
  50092. * @param name Name of the animation range
  50093. * @returns Nullable animation range
  50094. */
  50095. Animation.prototype.getRange = function (name) {
  50096. return this._ranges[name];
  50097. };
  50098. /**
  50099. * Gets the key frames from the animation
  50100. * @returns The key frames of the animation
  50101. */
  50102. Animation.prototype.getKeys = function () {
  50103. return this._keys;
  50104. };
  50105. /**
  50106. * Gets the highest frame rate of the animation
  50107. * @returns Highest frame rate of the animation
  50108. */
  50109. Animation.prototype.getHighestFrame = function () {
  50110. var ret = 0;
  50111. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50112. if (ret < this._keys[key].frame) {
  50113. ret = this._keys[key].frame;
  50114. }
  50115. }
  50116. return ret;
  50117. };
  50118. /**
  50119. * Gets the easing function of the animation
  50120. * @returns Easing function of the animation
  50121. */
  50122. Animation.prototype.getEasingFunction = function () {
  50123. return this._easingFunction;
  50124. };
  50125. /**
  50126. * Sets the easing function of the animation
  50127. * @param easingFunction A custom mathematical formula for animation
  50128. */
  50129. Animation.prototype.setEasingFunction = function (easingFunction) {
  50130. this._easingFunction = easingFunction;
  50131. };
  50132. /**
  50133. * Interpolates a scalar linearly
  50134. * @param startValue Start value of the animation curve
  50135. * @param endValue End value of the animation curve
  50136. * @param gradient Scalar amount to interpolate
  50137. * @returns Interpolated scalar value
  50138. */
  50139. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50140. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50141. };
  50142. /**
  50143. * Interpolates a scalar cubically
  50144. * @param startValue Start value of the animation curve
  50145. * @param outTangent End tangent of the animation
  50146. * @param endValue End value of the animation curve
  50147. * @param inTangent Start tangent of the animation curve
  50148. * @param gradient Scalar amount to interpolate
  50149. * @returns Interpolated scalar value
  50150. */
  50151. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50152. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50153. };
  50154. /**
  50155. * Interpolates a quaternion using a spherical linear interpolation
  50156. * @param startValue Start value of the animation curve
  50157. * @param endValue End value of the animation curve
  50158. * @param gradient Scalar amount to interpolate
  50159. * @returns Interpolated quaternion value
  50160. */
  50161. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50162. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50163. };
  50164. /**
  50165. * Interpolates a quaternion cubically
  50166. * @param startValue Start value of the animation curve
  50167. * @param outTangent End tangent of the animation curve
  50168. * @param endValue End value of the animation curve
  50169. * @param inTangent Start tangent of the animation curve
  50170. * @param gradient Scalar amount to interpolate
  50171. * @returns Interpolated quaternion value
  50172. */
  50173. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50174. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50175. };
  50176. /**
  50177. * Interpolates a Vector3 linearl
  50178. * @param startValue Start value of the animation curve
  50179. * @param endValue End value of the animation curve
  50180. * @param gradient Scalar amount to interpolate
  50181. * @returns Interpolated scalar value
  50182. */
  50183. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50184. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50185. };
  50186. /**
  50187. * Interpolates a Vector3 cubically
  50188. * @param startValue Start value of the animation curve
  50189. * @param outTangent End tangent of the animation
  50190. * @param endValue End value of the animation curve
  50191. * @param inTangent Start tangent of the animation curve
  50192. * @param gradient Scalar amount to interpolate
  50193. * @returns InterpolatedVector3 value
  50194. */
  50195. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50196. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50197. };
  50198. /**
  50199. * Interpolates a Vector2 linearly
  50200. * @param startValue Start value of the animation curve
  50201. * @param endValue End value of the animation curve
  50202. * @param gradient Scalar amount to interpolate
  50203. * @returns Interpolated Vector2 value
  50204. */
  50205. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50206. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50207. };
  50208. /**
  50209. * Interpolates a Vector2 cubically
  50210. * @param startValue Start value of the animation curve
  50211. * @param outTangent End tangent of the animation
  50212. * @param endValue End value of the animation curve
  50213. * @param inTangent Start tangent of the animation curve
  50214. * @param gradient Scalar amount to interpolate
  50215. * @returns Interpolated Vector2 value
  50216. */
  50217. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50218. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50219. };
  50220. /**
  50221. * Interpolates a size linearly
  50222. * @param startValue Start value of the animation curve
  50223. * @param endValue End value of the animation curve
  50224. * @param gradient Scalar amount to interpolate
  50225. * @returns Interpolated Size value
  50226. */
  50227. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50228. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50229. };
  50230. /**
  50231. * Interpolates a Color3 linearly
  50232. * @param startValue Start value of the animation curve
  50233. * @param endValue End value of the animation curve
  50234. * @param gradient Scalar amount to interpolate
  50235. * @returns Interpolated Color3 value
  50236. */
  50237. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50238. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50239. };
  50240. /**
  50241. * @hidden Internal use only
  50242. */
  50243. Animation.prototype._getKeyValue = function (value) {
  50244. if (typeof value === "function") {
  50245. return value();
  50246. }
  50247. return value;
  50248. };
  50249. /**
  50250. * @hidden Internal use only
  50251. */
  50252. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50253. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50254. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50255. }
  50256. var keys = this.getKeys();
  50257. // Try to get a hash to find the right key
  50258. 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));
  50259. if (keys[startKeyIndex].frame >= currentFrame) {
  50260. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50261. startKeyIndex--;
  50262. }
  50263. }
  50264. for (var key = startKeyIndex; key < keys.length; key++) {
  50265. var endKey = keys[key + 1];
  50266. if (endKey.frame >= currentFrame) {
  50267. var startKey = keys[key];
  50268. var startValue = this._getKeyValue(startKey.value);
  50269. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50270. return startValue;
  50271. }
  50272. var endValue = this._getKeyValue(endKey.value);
  50273. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50274. var frameDelta = endKey.frame - startKey.frame;
  50275. // gradient : percent of currentFrame between the frame inf and the frame sup
  50276. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50277. // check for easingFunction and correction of gradient
  50278. var easingFunction = this.getEasingFunction();
  50279. if (easingFunction != null) {
  50280. gradient = easingFunction.ease(gradient);
  50281. }
  50282. switch (this.dataType) {
  50283. // Float
  50284. case Animation.ANIMATIONTYPE_FLOAT:
  50285. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50286. switch (loopMode) {
  50287. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50288. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50289. return floatValue;
  50290. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50291. return offsetValue * repeatCount + floatValue;
  50292. }
  50293. break;
  50294. // Quaternion
  50295. case Animation.ANIMATIONTYPE_QUATERNION:
  50296. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50297. switch (loopMode) {
  50298. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50299. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50300. return quatValue;
  50301. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50302. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50303. }
  50304. return quatValue;
  50305. // Vector3
  50306. case Animation.ANIMATIONTYPE_VECTOR3:
  50307. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50308. switch (loopMode) {
  50309. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50310. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50311. return vec3Value;
  50312. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50313. return vec3Value.add(offsetValue.scale(repeatCount));
  50314. }
  50315. // Vector2
  50316. case Animation.ANIMATIONTYPE_VECTOR2:
  50317. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50318. switch (loopMode) {
  50319. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50320. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50321. return vec2Value;
  50322. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50323. return vec2Value.add(offsetValue.scale(repeatCount));
  50324. }
  50325. // Size
  50326. case Animation.ANIMATIONTYPE_SIZE:
  50327. switch (loopMode) {
  50328. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50329. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50330. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50331. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50332. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50333. }
  50334. // Color3
  50335. case Animation.ANIMATIONTYPE_COLOR3:
  50336. switch (loopMode) {
  50337. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50338. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50339. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50340. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50341. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50342. }
  50343. // Matrix
  50344. case Animation.ANIMATIONTYPE_MATRIX:
  50345. switch (loopMode) {
  50346. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50347. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50348. if (Animation.AllowMatricesInterpolation) {
  50349. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50350. }
  50351. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50352. return startValue;
  50353. }
  50354. default:
  50355. break;
  50356. }
  50357. break;
  50358. }
  50359. }
  50360. return this._getKeyValue(keys[keys.length - 1].value);
  50361. };
  50362. /**
  50363. * Defines the function to use to interpolate matrices
  50364. * @param startValue defines the start matrix
  50365. * @param endValue defines the end matrix
  50366. * @param gradient defines the gradient between both matrices
  50367. * @param result defines an optional target matrix where to store the interpolation
  50368. * @returns the interpolated matrix
  50369. */
  50370. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50371. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50372. if (result) {
  50373. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50374. return result;
  50375. }
  50376. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50377. }
  50378. if (result) {
  50379. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50380. return result;
  50381. }
  50382. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50383. };
  50384. /**
  50385. * Makes a copy of the animation
  50386. * @returns Cloned animation
  50387. */
  50388. Animation.prototype.clone = function () {
  50389. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50390. clone.enableBlending = this.enableBlending;
  50391. clone.blendingSpeed = this.blendingSpeed;
  50392. if (this._keys) {
  50393. clone.setKeys(this._keys);
  50394. }
  50395. if (this._ranges) {
  50396. clone._ranges = {};
  50397. for (var name in this._ranges) {
  50398. var range = this._ranges[name];
  50399. if (!range) {
  50400. continue;
  50401. }
  50402. clone._ranges[name] = range.clone();
  50403. }
  50404. }
  50405. return clone;
  50406. };
  50407. /**
  50408. * Sets the key frames of the animation
  50409. * @param values The animation key frames to set
  50410. */
  50411. Animation.prototype.setKeys = function (values) {
  50412. this._keys = values.slice(0);
  50413. };
  50414. /**
  50415. * Serializes the animation to an object
  50416. * @returns Serialized object
  50417. */
  50418. Animation.prototype.serialize = function () {
  50419. var serializationObject = {};
  50420. serializationObject.name = this.name;
  50421. serializationObject.property = this.targetProperty;
  50422. serializationObject.framePerSecond = this.framePerSecond;
  50423. serializationObject.dataType = this.dataType;
  50424. serializationObject.loopBehavior = this.loopMode;
  50425. serializationObject.enableBlending = this.enableBlending;
  50426. serializationObject.blendingSpeed = this.blendingSpeed;
  50427. var dataType = this.dataType;
  50428. serializationObject.keys = [];
  50429. var keys = this.getKeys();
  50430. for (var index = 0; index < keys.length; index++) {
  50431. var animationKey = keys[index];
  50432. var key = {};
  50433. key.frame = animationKey.frame;
  50434. switch (dataType) {
  50435. case Animation.ANIMATIONTYPE_FLOAT:
  50436. key.values = [animationKey.value];
  50437. break;
  50438. case Animation.ANIMATIONTYPE_QUATERNION:
  50439. case Animation.ANIMATIONTYPE_MATRIX:
  50440. case Animation.ANIMATIONTYPE_VECTOR3:
  50441. case Animation.ANIMATIONTYPE_COLOR3:
  50442. key.values = animationKey.value.asArray();
  50443. break;
  50444. }
  50445. serializationObject.keys.push(key);
  50446. }
  50447. serializationObject.ranges = [];
  50448. for (var name in this._ranges) {
  50449. var source = this._ranges[name];
  50450. if (!source) {
  50451. continue;
  50452. }
  50453. var range = {};
  50454. range.name = name;
  50455. range.from = source.from;
  50456. range.to = source.to;
  50457. serializationObject.ranges.push(range);
  50458. }
  50459. return serializationObject;
  50460. };
  50461. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50462. /**
  50463. * Get the float animation type
  50464. */
  50465. get: function () {
  50466. return Animation._ANIMATIONTYPE_FLOAT;
  50467. },
  50468. enumerable: true,
  50469. configurable: true
  50470. });
  50471. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50472. /**
  50473. * Get the Vector3 animation type
  50474. */
  50475. get: function () {
  50476. return Animation._ANIMATIONTYPE_VECTOR3;
  50477. },
  50478. enumerable: true,
  50479. configurable: true
  50480. });
  50481. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50482. /**
  50483. * Get the Vector2 animation type
  50484. */
  50485. get: function () {
  50486. return Animation._ANIMATIONTYPE_VECTOR2;
  50487. },
  50488. enumerable: true,
  50489. configurable: true
  50490. });
  50491. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50492. /**
  50493. * Get the Size animation type
  50494. */
  50495. get: function () {
  50496. return Animation._ANIMATIONTYPE_SIZE;
  50497. },
  50498. enumerable: true,
  50499. configurable: true
  50500. });
  50501. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50502. /**
  50503. * Get the Quaternion animation type
  50504. */
  50505. get: function () {
  50506. return Animation._ANIMATIONTYPE_QUATERNION;
  50507. },
  50508. enumerable: true,
  50509. configurable: true
  50510. });
  50511. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50512. /**
  50513. * Get the Matrix animation type
  50514. */
  50515. get: function () {
  50516. return Animation._ANIMATIONTYPE_MATRIX;
  50517. },
  50518. enumerable: true,
  50519. configurable: true
  50520. });
  50521. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50522. /**
  50523. * Get the Color3 animation type
  50524. */
  50525. get: function () {
  50526. return Animation._ANIMATIONTYPE_COLOR3;
  50527. },
  50528. enumerable: true,
  50529. configurable: true
  50530. });
  50531. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50532. /**
  50533. * Get the Relative Loop Mode
  50534. */
  50535. get: function () {
  50536. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50537. },
  50538. enumerable: true,
  50539. configurable: true
  50540. });
  50541. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50542. /**
  50543. * Get the Cycle Loop Mode
  50544. */
  50545. get: function () {
  50546. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50547. },
  50548. enumerable: true,
  50549. configurable: true
  50550. });
  50551. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50552. /**
  50553. * Get the Constant Loop Mode
  50554. */
  50555. get: function () {
  50556. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50557. },
  50558. enumerable: true,
  50559. configurable: true
  50560. });
  50561. /** @hidden */
  50562. Animation._UniversalLerp = function (left, right, amount) {
  50563. var constructor = left.constructor;
  50564. if (constructor.Lerp) { // Lerp supported
  50565. return constructor.Lerp(left, right, amount);
  50566. }
  50567. else if (constructor.Slerp) { // Slerp supported
  50568. return constructor.Slerp(left, right, amount);
  50569. }
  50570. else if (left.toFixed) { // Number
  50571. return left * (1.0 - amount) + amount * right;
  50572. }
  50573. else { // Blending not supported
  50574. return right;
  50575. }
  50576. };
  50577. /**
  50578. * Parses an animation object and creates an animation
  50579. * @param parsedAnimation Parsed animation object
  50580. * @returns Animation object
  50581. */
  50582. Animation.Parse = function (parsedAnimation) {
  50583. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50584. var dataType = parsedAnimation.dataType;
  50585. var keys = [];
  50586. var data;
  50587. var index;
  50588. if (parsedAnimation.enableBlending) {
  50589. animation.enableBlending = parsedAnimation.enableBlending;
  50590. }
  50591. if (parsedAnimation.blendingSpeed) {
  50592. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50593. }
  50594. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50595. var key = parsedAnimation.keys[index];
  50596. var inTangent;
  50597. var outTangent;
  50598. switch (dataType) {
  50599. case Animation.ANIMATIONTYPE_FLOAT:
  50600. data = key.values[0];
  50601. if (key.values.length >= 1) {
  50602. inTangent = key.values[1];
  50603. }
  50604. if (key.values.length >= 2) {
  50605. outTangent = key.values[2];
  50606. }
  50607. break;
  50608. case Animation.ANIMATIONTYPE_QUATERNION:
  50609. data = BABYLON.Quaternion.FromArray(key.values);
  50610. if (key.values.length >= 8) {
  50611. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50612. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50613. inTangent = _inTangent;
  50614. }
  50615. }
  50616. if (key.values.length >= 12) {
  50617. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50618. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50619. outTangent = _outTangent;
  50620. }
  50621. }
  50622. break;
  50623. case Animation.ANIMATIONTYPE_MATRIX:
  50624. data = BABYLON.Matrix.FromArray(key.values);
  50625. break;
  50626. case Animation.ANIMATIONTYPE_COLOR3:
  50627. data = BABYLON.Color3.FromArray(key.values);
  50628. break;
  50629. case Animation.ANIMATIONTYPE_VECTOR3:
  50630. default:
  50631. data = BABYLON.Vector3.FromArray(key.values);
  50632. break;
  50633. }
  50634. var keyData = {};
  50635. keyData.frame = key.frame;
  50636. keyData.value = data;
  50637. if (inTangent != undefined) {
  50638. keyData.inTangent = inTangent;
  50639. }
  50640. if (outTangent != undefined) {
  50641. keyData.outTangent = outTangent;
  50642. }
  50643. keys.push(keyData);
  50644. }
  50645. animation.setKeys(keys);
  50646. if (parsedAnimation.ranges) {
  50647. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50648. data = parsedAnimation.ranges[index];
  50649. animation.createRange(data.name, data.from, data.to);
  50650. }
  50651. }
  50652. return animation;
  50653. };
  50654. /**
  50655. * Appends the serialized animations from the source animations
  50656. * @param source Source containing the animations
  50657. * @param destination Target to store the animations
  50658. */
  50659. Animation.AppendSerializedAnimations = function (source, destination) {
  50660. if (source.animations) {
  50661. destination.animations = [];
  50662. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50663. var animation = source.animations[animationIndex];
  50664. destination.animations.push(animation.serialize());
  50665. }
  50666. }
  50667. };
  50668. /**
  50669. * Use matrix interpolation instead of using direct key value when animating matrices
  50670. */
  50671. Animation.AllowMatricesInterpolation = false;
  50672. /**
  50673. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50674. */
  50675. Animation.AllowMatrixDecomposeForInterpolation = true;
  50676. // Statics
  50677. /**
  50678. * Float animation type
  50679. */
  50680. Animation._ANIMATIONTYPE_FLOAT = 0;
  50681. /**
  50682. * Vector3 animation type
  50683. */
  50684. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50685. /**
  50686. * Quaternion animation type
  50687. */
  50688. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50689. /**
  50690. * Matrix animation type
  50691. */
  50692. Animation._ANIMATIONTYPE_MATRIX = 3;
  50693. /**
  50694. * Color3 animation type
  50695. */
  50696. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50697. /**
  50698. * Vector2 animation type
  50699. */
  50700. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50701. /**
  50702. * Size animation type
  50703. */
  50704. Animation._ANIMATIONTYPE_SIZE = 6;
  50705. /**
  50706. * Relative Loop Mode
  50707. */
  50708. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50709. /**
  50710. * Cycle Loop Mode
  50711. */
  50712. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50713. /**
  50714. * Constant Loop Mode
  50715. */
  50716. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50717. return Animation;
  50718. }());
  50719. BABYLON.Animation = Animation;
  50720. })(BABYLON || (BABYLON = {}));
  50721. //# sourceMappingURL=babylon.animation.js.map
  50722. var BABYLON;
  50723. (function (BABYLON) {
  50724. /**
  50725. * This class defines the direct association between an animation and a target
  50726. */
  50727. var TargetedAnimation = /** @class */ (function () {
  50728. function TargetedAnimation() {
  50729. }
  50730. return TargetedAnimation;
  50731. }());
  50732. BABYLON.TargetedAnimation = TargetedAnimation;
  50733. /**
  50734. * Use this class to create coordinated animations on multiple targets
  50735. */
  50736. var AnimationGroup = /** @class */ (function () {
  50737. function AnimationGroup(name, scene) {
  50738. if (scene === void 0) { scene = null; }
  50739. this.name = name;
  50740. this._targetedAnimations = new Array();
  50741. this._animatables = new Array();
  50742. this._from = Number.MAX_VALUE;
  50743. this._to = -Number.MAX_VALUE;
  50744. this._speedRatio = 1;
  50745. this.onAnimationEndObservable = new BABYLON.Observable();
  50746. /**
  50747. * This observable will notify when all animations have ended.
  50748. */
  50749. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50750. /**
  50751. * This observable will notify when all animations have paused.
  50752. */
  50753. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50754. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50755. this._scene.animationGroups.push(this);
  50756. }
  50757. Object.defineProperty(AnimationGroup.prototype, "from", {
  50758. /**
  50759. * Gets the first frame
  50760. */
  50761. get: function () {
  50762. return this._from;
  50763. },
  50764. enumerable: true,
  50765. configurable: true
  50766. });
  50767. Object.defineProperty(AnimationGroup.prototype, "to", {
  50768. /**
  50769. * Gets the last frame
  50770. */
  50771. get: function () {
  50772. return this._to;
  50773. },
  50774. enumerable: true,
  50775. configurable: true
  50776. });
  50777. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50778. /**
  50779. * Define if the animations are started
  50780. */
  50781. get: function () {
  50782. return this._isStarted;
  50783. },
  50784. enumerable: true,
  50785. configurable: true
  50786. });
  50787. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50788. /**
  50789. * Gets or sets the speed ratio to use for all animations
  50790. */
  50791. get: function () {
  50792. return this._speedRatio;
  50793. },
  50794. /**
  50795. * Gets or sets the speed ratio to use for all animations
  50796. */
  50797. set: function (value) {
  50798. if (this._speedRatio === value) {
  50799. return;
  50800. }
  50801. this._speedRatio = value;
  50802. for (var index = 0; index < this._animatables.length; index++) {
  50803. var animatable = this._animatables[index];
  50804. animatable.speedRatio = this._speedRatio;
  50805. }
  50806. },
  50807. enumerable: true,
  50808. configurable: true
  50809. });
  50810. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50811. /**
  50812. * Gets the targeted animations for this animation group
  50813. */
  50814. get: function () {
  50815. return this._targetedAnimations;
  50816. },
  50817. enumerable: true,
  50818. configurable: true
  50819. });
  50820. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50821. /**
  50822. * returning the list of animatables controlled by this animation group.
  50823. */
  50824. get: function () {
  50825. return this._animatables;
  50826. },
  50827. enumerable: true,
  50828. configurable: true
  50829. });
  50830. /**
  50831. * Add an animation (with its target) in the group
  50832. * @param animation defines the animation we want to add
  50833. * @param target defines the target of the animation
  50834. * @returns the {BABYLON.TargetedAnimation} object
  50835. */
  50836. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50837. var targetedAnimation = {
  50838. animation: animation,
  50839. target: target
  50840. };
  50841. var keys = animation.getKeys();
  50842. if (this._from > keys[0].frame) {
  50843. this._from = keys[0].frame;
  50844. }
  50845. if (this._to < keys[keys.length - 1].frame) {
  50846. this._to = keys[keys.length - 1].frame;
  50847. }
  50848. this._targetedAnimations.push(targetedAnimation);
  50849. return targetedAnimation;
  50850. };
  50851. /**
  50852. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50853. * It can add constant keys at begin or end
  50854. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50855. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50856. */
  50857. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50858. if (beginFrame === void 0) { beginFrame = null; }
  50859. if (endFrame === void 0) { endFrame = null; }
  50860. if (beginFrame == null)
  50861. beginFrame = this._from;
  50862. if (endFrame == null)
  50863. endFrame = this._to;
  50864. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50865. var targetedAnimation = this._targetedAnimations[index];
  50866. var keys = targetedAnimation.animation.getKeys();
  50867. var startKey = keys[0];
  50868. var endKey = keys[keys.length - 1];
  50869. if (startKey.frame > beginFrame) {
  50870. var newKey = {
  50871. frame: beginFrame,
  50872. value: startKey.value,
  50873. inTangent: startKey.inTangent,
  50874. outTangent: startKey.outTangent,
  50875. interpolation: startKey.interpolation
  50876. };
  50877. keys.splice(0, 0, newKey);
  50878. }
  50879. if (endKey.frame < endFrame) {
  50880. var newKey = {
  50881. frame: endFrame,
  50882. value: endKey.value,
  50883. inTangent: endKey.outTangent,
  50884. outTangent: endKey.outTangent,
  50885. interpolation: endKey.interpolation
  50886. };
  50887. keys.push(newKey);
  50888. }
  50889. }
  50890. this._from = beginFrame;
  50891. this._to = endFrame;
  50892. return this;
  50893. };
  50894. /**
  50895. * Start all animations on given targets
  50896. * @param loop defines if animations must loop
  50897. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50898. * @param from defines the from key (optional)
  50899. * @param to defines the to key (optional)
  50900. * @returns the current animation group
  50901. */
  50902. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50903. var _this = this;
  50904. if (loop === void 0) { loop = false; }
  50905. if (speedRatio === void 0) { speedRatio = 1; }
  50906. if (this._isStarted || this._targetedAnimations.length === 0) {
  50907. return this;
  50908. }
  50909. var _loop_1 = function (targetedAnimation) {
  50910. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50911. animatable.onAnimationEnd = function () {
  50912. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50913. _this._checkAnimationGroupEnded(animatable);
  50914. };
  50915. this_1._animatables.push(animatable);
  50916. };
  50917. var this_1 = this;
  50918. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50919. var targetedAnimation = _a[_i];
  50920. _loop_1(targetedAnimation);
  50921. }
  50922. this._speedRatio = speedRatio;
  50923. this._isStarted = true;
  50924. return this;
  50925. };
  50926. /**
  50927. * Pause all animations
  50928. */
  50929. AnimationGroup.prototype.pause = function () {
  50930. if (!this._isStarted) {
  50931. return this;
  50932. }
  50933. for (var index = 0; index < this._animatables.length; index++) {
  50934. var animatable = this._animatables[index];
  50935. animatable.pause();
  50936. }
  50937. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50938. return this;
  50939. };
  50940. /**
  50941. * Play all animations to initial state
  50942. * This function will start() the animations if they were not started or will restart() them if they were paused
  50943. * @param loop defines if animations must loop
  50944. */
  50945. AnimationGroup.prototype.play = function (loop) {
  50946. // only if all animatables are ready and exist
  50947. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50948. if (loop !== undefined) {
  50949. for (var index = 0; index < this._animatables.length; index++) {
  50950. var animatable = this._animatables[index];
  50951. animatable.loopAnimation = loop;
  50952. }
  50953. }
  50954. this.restart();
  50955. }
  50956. else {
  50957. this.stop();
  50958. this.start(loop, this._speedRatio);
  50959. }
  50960. return this;
  50961. };
  50962. /**
  50963. * Reset all animations to initial state
  50964. */
  50965. AnimationGroup.prototype.reset = function () {
  50966. if (!this._isStarted) {
  50967. return this;
  50968. }
  50969. for (var index = 0; index < this._animatables.length; index++) {
  50970. var animatable = this._animatables[index];
  50971. animatable.reset();
  50972. }
  50973. return this;
  50974. };
  50975. /**
  50976. * Restart animations from key 0
  50977. */
  50978. AnimationGroup.prototype.restart = function () {
  50979. if (!this._isStarted) {
  50980. return this;
  50981. }
  50982. for (var index = 0; index < this._animatables.length; index++) {
  50983. var animatable = this._animatables[index];
  50984. animatable.restart();
  50985. }
  50986. return this;
  50987. };
  50988. /**
  50989. * Stop all animations
  50990. */
  50991. AnimationGroup.prototype.stop = function () {
  50992. if (!this._isStarted) {
  50993. return this;
  50994. }
  50995. var list = this._animatables.slice();
  50996. for (var index = 0; index < list.length; index++) {
  50997. list[index].stop();
  50998. }
  50999. this._isStarted = false;
  51000. return this;
  51001. };
  51002. /**
  51003. * Set animation weight for all animatables
  51004. * @param weight defines the weight to use
  51005. * @return the animationGroup
  51006. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51007. */
  51008. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51009. for (var index = 0; index < this._animatables.length; index++) {
  51010. var animatable = this._animatables[index];
  51011. animatable.weight = weight;
  51012. }
  51013. return this;
  51014. };
  51015. /**
  51016. * Synchronize and normalize all animatables with a source animatable
  51017. * @param root defines the root animatable to synchronize with
  51018. * @return the animationGroup
  51019. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51020. */
  51021. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51022. for (var index = 0; index < this._animatables.length; index++) {
  51023. var animatable = this._animatables[index];
  51024. animatable.syncWith(root);
  51025. }
  51026. return this;
  51027. };
  51028. /**
  51029. * Goes to a specific frame in this animation group
  51030. * @param frame the frame number to go to
  51031. * @return the animationGroup
  51032. */
  51033. AnimationGroup.prototype.goToFrame = function (frame) {
  51034. if (!this._isStarted) {
  51035. return this;
  51036. }
  51037. for (var index = 0; index < this._animatables.length; index++) {
  51038. var animatable = this._animatables[index];
  51039. animatable.goToFrame(frame);
  51040. }
  51041. return this;
  51042. };
  51043. /**
  51044. * Dispose all associated resources
  51045. */
  51046. AnimationGroup.prototype.dispose = function () {
  51047. this._targetedAnimations = [];
  51048. this._animatables = [];
  51049. var index = this._scene.animationGroups.indexOf(this);
  51050. if (index > -1) {
  51051. this._scene.animationGroups.splice(index, 1);
  51052. }
  51053. };
  51054. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51055. // animatable should be taken out of the array
  51056. var idx = this._animatables.indexOf(animatable);
  51057. if (idx > -1) {
  51058. this._animatables.splice(idx, 1);
  51059. }
  51060. // all animatables were removed? animation group ended!
  51061. if (this._animatables.length === 0) {
  51062. this._isStarted = false;
  51063. this.onAnimationGroupEndObservable.notifyObservers(this);
  51064. }
  51065. };
  51066. return AnimationGroup;
  51067. }());
  51068. BABYLON.AnimationGroup = AnimationGroup;
  51069. })(BABYLON || (BABYLON = {}));
  51070. //# sourceMappingURL=babylon.animationGroup.js.map
  51071. var BABYLON;
  51072. (function (BABYLON) {
  51073. // Static values to help the garbage collector
  51074. // Quaternion
  51075. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51076. // Vector3
  51077. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51078. // Vector2
  51079. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51080. // Size
  51081. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51082. // Color3
  51083. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51084. /**
  51085. * Defines a runtime animation
  51086. */
  51087. var RuntimeAnimation = /** @class */ (function () {
  51088. /**
  51089. * Create a new RuntimeAnimation object
  51090. * @param target defines the target of the animation
  51091. * @param animation defines the source animation object
  51092. * @param scene defines the hosting scene
  51093. * @param host defines the initiating Animatable
  51094. */
  51095. function RuntimeAnimation(target, animation, scene, host) {
  51096. var _this = this;
  51097. this._events = new Array();
  51098. /**
  51099. * The current frame of the runtime animation
  51100. */
  51101. this._currentFrame = 0;
  51102. /**
  51103. * The original value of the runtime animation
  51104. */
  51105. this._originalValue = new Array();
  51106. /**
  51107. * The offsets cache of the runtime animation
  51108. */
  51109. this._offsetsCache = {};
  51110. /**
  51111. * The high limits cache of the runtime animation
  51112. */
  51113. this._highLimitsCache = {};
  51114. /**
  51115. * Specifies if the runtime animation has been stopped
  51116. */
  51117. this._stopped = false;
  51118. /**
  51119. * The blending factor of the runtime animation
  51120. */
  51121. this._blendingFactor = 0;
  51122. /**
  51123. * The target path of the runtime animation
  51124. */
  51125. this._targetPath = "";
  51126. /**
  51127. * The weight of the runtime animation
  51128. */
  51129. this._weight = 1.0;
  51130. /**
  51131. * The ratio offset of the runtime animation
  51132. */
  51133. this._ratioOffset = 0;
  51134. /**
  51135. * The previous delay of the runtime animation
  51136. */
  51137. this._previousDelay = 0;
  51138. /**
  51139. * The previous ratio of the runtime animation
  51140. */
  51141. this._previousRatio = 0;
  51142. this._animation = animation;
  51143. this._target = target;
  51144. this._scene = scene;
  51145. this._host = host;
  51146. animation._runtimeAnimations.push(this);
  51147. // Cloning events locally
  51148. var events = animation.getEvents();
  51149. if (events && events.length > 0) {
  51150. events.forEach(function (e) {
  51151. _this._events.push(e._clone());
  51152. });
  51153. }
  51154. }
  51155. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51156. /**
  51157. * Gets the current frame of the runtime animation
  51158. */
  51159. get: function () {
  51160. return this._currentFrame;
  51161. },
  51162. enumerable: true,
  51163. configurable: true
  51164. });
  51165. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51166. /**
  51167. * Gets the weight of the runtime animation
  51168. */
  51169. get: function () {
  51170. return this._weight;
  51171. },
  51172. enumerable: true,
  51173. configurable: true
  51174. });
  51175. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51176. /**
  51177. * Gets the current value of the runtime animation
  51178. */
  51179. get: function () {
  51180. return this._currentValue;
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51186. /**
  51187. * Gets the target path of the runtime animation
  51188. */
  51189. get: function () {
  51190. return this._targetPath;
  51191. },
  51192. enumerable: true,
  51193. configurable: true
  51194. });
  51195. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51196. /**
  51197. * Gets the actual target of the runtime animation
  51198. */
  51199. get: function () {
  51200. return this._activeTarget;
  51201. },
  51202. enumerable: true,
  51203. configurable: true
  51204. });
  51205. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51206. /**
  51207. * Gets the animation from the runtime animation
  51208. */
  51209. get: function () {
  51210. return this._animation;
  51211. },
  51212. enumerable: true,
  51213. configurable: true
  51214. });
  51215. /**
  51216. * Resets the runtime animation to the beginning
  51217. * @param restoreOriginal defines whether to restore the target property to the original value
  51218. */
  51219. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51220. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51221. if (restoreOriginal) {
  51222. if (this._target instanceof Array) {
  51223. var index = 0;
  51224. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51225. var target = _a[_i];
  51226. if (this._originalValue[index] !== undefined) {
  51227. this._setValue(target, this._originalValue[index], -1);
  51228. }
  51229. index++;
  51230. }
  51231. }
  51232. else {
  51233. if (this._originalValue[0] !== undefined) {
  51234. this._setValue(this._target, this._originalValue[0], -1);
  51235. }
  51236. }
  51237. }
  51238. this._offsetsCache = {};
  51239. this._highLimitsCache = {};
  51240. this._currentFrame = 0;
  51241. this._blendingFactor = 0;
  51242. this._originalValue = new Array();
  51243. // Events
  51244. for (var index = 0; index < this._events.length; index++) {
  51245. this._events[index].isDone = false;
  51246. }
  51247. };
  51248. /**
  51249. * Specifies if the runtime animation is stopped
  51250. * @returns Boolean specifying if the runtime animation is stopped
  51251. */
  51252. RuntimeAnimation.prototype.isStopped = function () {
  51253. return this._stopped;
  51254. };
  51255. /**
  51256. * Disposes of the runtime animation
  51257. */
  51258. RuntimeAnimation.prototype.dispose = function () {
  51259. var index = this._animation.runtimeAnimations.indexOf(this);
  51260. if (index > -1) {
  51261. this._animation.runtimeAnimations.splice(index, 1);
  51262. }
  51263. };
  51264. /**
  51265. * Interpolates the animation from the current frame
  51266. * @param currentFrame The frame to interpolate the animation to
  51267. * @param repeatCount The number of times that the animation should loop
  51268. * @param loopMode The type of looping mode to use
  51269. * @param offsetValue Animation offset value
  51270. * @param highLimitValue The high limit value
  51271. * @returns The interpolated value
  51272. */
  51273. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51274. this._currentFrame = currentFrame;
  51275. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51276. this._workValue = BABYLON.Matrix.Zero();
  51277. }
  51278. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51279. };
  51280. /**
  51281. * Apply the interpolated value to the target
  51282. * @param currentValue defines the value computed by the animation
  51283. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51284. */
  51285. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51286. if (weight === void 0) { weight = 1.0; }
  51287. if (this._target instanceof Array) {
  51288. var index = 0;
  51289. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51290. var target = _a[_i];
  51291. this._setValue(target, currentValue, weight, index);
  51292. index++;
  51293. }
  51294. }
  51295. else {
  51296. this._setValue(this._target, currentValue, weight);
  51297. }
  51298. };
  51299. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51300. if (targetIndex === void 0) { targetIndex = 0; }
  51301. // Set value
  51302. var path;
  51303. var destination;
  51304. var targetPropertyPath = this._animation.targetPropertyPath;
  51305. if (targetPropertyPath.length > 1) {
  51306. var property = target[targetPropertyPath[0]];
  51307. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51308. property = property[targetPropertyPath[index]];
  51309. }
  51310. path = targetPropertyPath[targetPropertyPath.length - 1];
  51311. destination = property;
  51312. }
  51313. else {
  51314. path = targetPropertyPath[0];
  51315. destination = target;
  51316. }
  51317. this._targetPath = path;
  51318. this._activeTarget = destination;
  51319. this._weight = weight;
  51320. if (this._originalValue[targetIndex] === undefined) {
  51321. var originalValue = void 0;
  51322. if (destination.getRestPose && path === "_matrix") { // For bones
  51323. originalValue = destination.getRestPose();
  51324. }
  51325. else {
  51326. originalValue = destination[path];
  51327. }
  51328. if (originalValue && originalValue.clone) {
  51329. this._originalValue[targetIndex] = originalValue.clone();
  51330. }
  51331. else {
  51332. this._originalValue[targetIndex] = originalValue;
  51333. }
  51334. }
  51335. // Blending
  51336. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51337. if (enableBlending && this._blendingFactor <= 1.0) {
  51338. if (!this._originalBlendValue) {
  51339. var originalValue = destination[path];
  51340. if (originalValue.clone) {
  51341. this._originalBlendValue = originalValue.clone();
  51342. }
  51343. else {
  51344. this._originalBlendValue = originalValue;
  51345. }
  51346. }
  51347. if (this._originalBlendValue.m) { // Matrix
  51348. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51349. if (this._currentValue) {
  51350. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51351. }
  51352. else {
  51353. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51354. }
  51355. }
  51356. else {
  51357. if (this._currentValue) {
  51358. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51359. }
  51360. else {
  51361. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51362. }
  51363. }
  51364. }
  51365. else {
  51366. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51367. }
  51368. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51369. this._blendingFactor += blendingSpeed;
  51370. }
  51371. else {
  51372. this._currentValue = currentValue;
  51373. }
  51374. if (weight !== -1.0) {
  51375. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51376. }
  51377. else {
  51378. destination[path] = this._currentValue;
  51379. }
  51380. if (target.markAsDirty) {
  51381. target.markAsDirty(this._animation.targetProperty);
  51382. }
  51383. };
  51384. /**
  51385. * Gets the loop pmode of the runtime animation
  51386. * @returns Loop Mode
  51387. */
  51388. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51389. if (this._target && this._target.animationPropertiesOverride) {
  51390. return this._target.animationPropertiesOverride.loopMode;
  51391. }
  51392. return this._animation.loopMode;
  51393. };
  51394. /**
  51395. * Move the current animation to a given frame
  51396. * @param frame defines the frame to move to
  51397. */
  51398. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51399. var keys = this._animation.getKeys();
  51400. if (frame < keys[0].frame) {
  51401. frame = keys[0].frame;
  51402. }
  51403. else if (frame > keys[keys.length - 1].frame) {
  51404. frame = keys[keys.length - 1].frame;
  51405. }
  51406. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51407. this.setValue(currentValue, -1);
  51408. };
  51409. /**
  51410. * @hidden Internal use only
  51411. */
  51412. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51413. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51414. this._ratioOffset = this._previousRatio - newRatio;
  51415. };
  51416. /**
  51417. * Execute the current animation
  51418. * @param delay defines the delay to add to the current frame
  51419. * @param from defines the lower bound of the animation range
  51420. * @param to defines the upper bound of the animation range
  51421. * @param loop defines if the current animation must loop
  51422. * @param speedRatio defines the current speed ratio
  51423. * @param weight defines the weight of the animation (default is -1 so no weight)
  51424. * @returns a boolean indicating if the animation is running
  51425. */
  51426. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51427. if (weight === void 0) { weight = -1.0; }
  51428. var targetPropertyPath = this._animation.targetPropertyPath;
  51429. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51430. this._stopped = true;
  51431. return false;
  51432. }
  51433. var returnValue = true;
  51434. var keys = this._animation.getKeys();
  51435. // Adding a start key at frame 0 if missing
  51436. if (keys[0].frame !== 0) {
  51437. var newKey = { frame: 0, value: keys[0].value };
  51438. keys.splice(0, 0, newKey);
  51439. }
  51440. // Adding a duplicate key when there is only one key at frame zero
  51441. else if (keys.length === 1) {
  51442. var newKey = { frame: 0.001, value: keys[0].value };
  51443. keys.push(newKey);
  51444. }
  51445. // Check limits
  51446. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51447. from = keys[0].frame;
  51448. }
  51449. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51450. to = keys[keys.length - 1].frame;
  51451. }
  51452. //to and from cannot be the same key
  51453. if (from === to) {
  51454. if (from > keys[0].frame) {
  51455. from--;
  51456. }
  51457. else if (to < keys[keys.length - 1].frame) {
  51458. to++;
  51459. }
  51460. }
  51461. // Compute ratio
  51462. var range = to - from;
  51463. var offsetValue;
  51464. // ratio represents the frame delta between from and to
  51465. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51466. var highLimitValue = 0;
  51467. this._previousDelay = delay;
  51468. this._previousRatio = ratio;
  51469. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51470. returnValue = false;
  51471. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51472. }
  51473. else {
  51474. // Get max value if required
  51475. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51476. var keyOffset = to.toString() + from.toString();
  51477. if (!this._offsetsCache[keyOffset]) {
  51478. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51479. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51480. switch (this._animation.dataType) {
  51481. // Float
  51482. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51483. this._offsetsCache[keyOffset] = toValue - fromValue;
  51484. break;
  51485. // Quaternion
  51486. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51487. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51488. break;
  51489. // Vector3
  51490. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51491. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51492. // Vector2
  51493. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51494. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51495. // Size
  51496. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51497. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51498. // Color3
  51499. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51500. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51501. default:
  51502. break;
  51503. }
  51504. this._highLimitsCache[keyOffset] = toValue;
  51505. }
  51506. highLimitValue = this._highLimitsCache[keyOffset];
  51507. offsetValue = this._offsetsCache[keyOffset];
  51508. }
  51509. }
  51510. if (offsetValue === undefined) {
  51511. switch (this._animation.dataType) {
  51512. // Float
  51513. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51514. offsetValue = 0;
  51515. break;
  51516. // Quaternion
  51517. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51518. offsetValue = _staticOffsetValueQuaternion;
  51519. break;
  51520. // Vector3
  51521. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51522. offsetValue = _staticOffsetValueVector3;
  51523. break;
  51524. // Vector2
  51525. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51526. offsetValue = _staticOffsetValueVector2;
  51527. break;
  51528. // Size
  51529. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51530. offsetValue = _staticOffsetValueSize;
  51531. break;
  51532. // Color3
  51533. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51534. offsetValue = _staticOffsetValueColor3;
  51535. }
  51536. }
  51537. // Compute value
  51538. var repeatCount = (ratio / range) >> 0;
  51539. var currentFrame = returnValue ? from + ratio % range : to;
  51540. // Need to normalize?
  51541. if (this._host && this._host.syncRoot) {
  51542. var syncRoot = this._host.syncRoot;
  51543. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51544. currentFrame = from + (to - from) * hostNormalizedFrame;
  51545. }
  51546. // Reset events if looping
  51547. var events = this._events;
  51548. if (range > 0 && this.currentFrame > currentFrame ||
  51549. range < 0 && this.currentFrame < currentFrame) {
  51550. // Need to reset animation events
  51551. for (var index = 0; index < events.length; index++) {
  51552. if (!events[index].onlyOnce) {
  51553. // reset event, the animation is looping
  51554. events[index].isDone = false;
  51555. }
  51556. }
  51557. }
  51558. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51559. // Set value
  51560. this.setValue(currentValue, weight);
  51561. // Check events
  51562. for (var index = 0; index < events.length; index++) {
  51563. // Make sure current frame has passed event frame and that event frame is within the current range
  51564. // Also, handle both forward and reverse animations
  51565. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51566. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51567. var event = events[index];
  51568. if (!event.isDone) {
  51569. // If event should be done only once, remove it.
  51570. if (event.onlyOnce) {
  51571. events.splice(index, 1);
  51572. index--;
  51573. }
  51574. event.isDone = true;
  51575. event.action(currentFrame);
  51576. } // Don't do anything if the event has already be done.
  51577. }
  51578. }
  51579. if (!returnValue) {
  51580. this._stopped = true;
  51581. }
  51582. return returnValue;
  51583. };
  51584. return RuntimeAnimation;
  51585. }());
  51586. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51587. })(BABYLON || (BABYLON = {}));
  51588. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51589. var BABYLON;
  51590. (function (BABYLON) {
  51591. /**
  51592. * Class used to store an actual running animation
  51593. */
  51594. var Animatable = /** @class */ (function () {
  51595. /**
  51596. * Creates a new Animatable
  51597. * @param scene defines the hosting scene
  51598. * @param target defines the target object
  51599. * @param fromFrame defines the starting frame number (default is 0)
  51600. * @param toFrame defines the ending frame number (default is 100)
  51601. * @param loopAnimation defines if the animation must loop (default is false)
  51602. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51603. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51604. * @param animations defines a group of animation to add to the new Animatable
  51605. */
  51606. function Animatable(scene,
  51607. /** defines the target object */
  51608. target,
  51609. /** defines the starting frame number (default is 0) */
  51610. fromFrame,
  51611. /** defines the ending frame number (default is 100) */
  51612. toFrame,
  51613. /** defines if the animation must loop (default is false) */
  51614. loopAnimation, speedRatio,
  51615. /** defines a callback to call when animation ends if it is not looping */
  51616. onAnimationEnd, animations) {
  51617. if (fromFrame === void 0) { fromFrame = 0; }
  51618. if (toFrame === void 0) { toFrame = 100; }
  51619. if (loopAnimation === void 0) { loopAnimation = false; }
  51620. if (speedRatio === void 0) { speedRatio = 1.0; }
  51621. this.target = target;
  51622. this.fromFrame = fromFrame;
  51623. this.toFrame = toFrame;
  51624. this.loopAnimation = loopAnimation;
  51625. this.onAnimationEnd = onAnimationEnd;
  51626. this._localDelayOffset = null;
  51627. this._pausedDelay = null;
  51628. this._runtimeAnimations = new Array();
  51629. this._paused = false;
  51630. this._speedRatio = 1;
  51631. this._weight = -1.0;
  51632. /**
  51633. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51634. * This will only apply for non looping animation (default is true)
  51635. */
  51636. this.disposeOnEnd = true;
  51637. /**
  51638. * Gets a boolean indicating if the animation has started
  51639. */
  51640. this.animationStarted = false;
  51641. /**
  51642. * Observer raised when the animation ends
  51643. */
  51644. this.onAnimationEndObservable = new BABYLON.Observable();
  51645. this._scene = scene;
  51646. if (animations) {
  51647. this.appendAnimations(target, animations);
  51648. }
  51649. this._speedRatio = speedRatio;
  51650. scene._activeAnimatables.push(this);
  51651. }
  51652. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51653. /**
  51654. * Gets the root Animatable used to synchronize and normalize animations
  51655. */
  51656. get: function () {
  51657. return this._syncRoot;
  51658. },
  51659. enumerable: true,
  51660. configurable: true
  51661. });
  51662. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51663. /**
  51664. * Gets the current frame of the first RuntimeAnimation
  51665. * Used to synchronize Animatables
  51666. */
  51667. get: function () {
  51668. if (this._runtimeAnimations.length === 0) {
  51669. return 0;
  51670. }
  51671. return this._runtimeAnimations[0].currentFrame;
  51672. },
  51673. enumerable: true,
  51674. configurable: true
  51675. });
  51676. Object.defineProperty(Animatable.prototype, "weight", {
  51677. /**
  51678. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51679. */
  51680. get: function () {
  51681. return this._weight;
  51682. },
  51683. set: function (value) {
  51684. if (value === -1) { // -1 is ok and means no weight
  51685. this._weight = -1;
  51686. return;
  51687. }
  51688. // Else weight must be in [0, 1] range
  51689. this._weight = Math.min(Math.max(value, 0), 1.0);
  51690. },
  51691. enumerable: true,
  51692. configurable: true
  51693. });
  51694. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51695. /**
  51696. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51697. */
  51698. get: function () {
  51699. return this._speedRatio;
  51700. },
  51701. set: function (value) {
  51702. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51703. var animation = this._runtimeAnimations[index];
  51704. animation._prepareForSpeedRatioChange(value);
  51705. }
  51706. this._speedRatio = value;
  51707. },
  51708. enumerable: true,
  51709. configurable: true
  51710. });
  51711. // Methods
  51712. /**
  51713. * Synchronize and normalize current Animatable with a source Animatable
  51714. * This is useful when using animation weights and when animations are not of the same length
  51715. * @param root defines the root Animatable to synchronize with
  51716. * @returns the current Animatable
  51717. */
  51718. Animatable.prototype.syncWith = function (root) {
  51719. this._syncRoot = root;
  51720. if (root) {
  51721. // Make sure this animatable will animate after the root
  51722. var index = this._scene._activeAnimatables.indexOf(this);
  51723. if (index > -1) {
  51724. this._scene._activeAnimatables.splice(index, 1);
  51725. this._scene._activeAnimatables.push(this);
  51726. }
  51727. }
  51728. return this;
  51729. };
  51730. /**
  51731. * Gets the list of runtime animations
  51732. * @returns an array of RuntimeAnimation
  51733. */
  51734. Animatable.prototype.getAnimations = function () {
  51735. return this._runtimeAnimations;
  51736. };
  51737. /**
  51738. * Adds more animations to the current animatable
  51739. * @param target defines the target of the animations
  51740. * @param animations defines the new animations to add
  51741. */
  51742. Animatable.prototype.appendAnimations = function (target, animations) {
  51743. for (var index = 0; index < animations.length; index++) {
  51744. var animation = animations[index];
  51745. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51746. }
  51747. };
  51748. /**
  51749. * Gets the source animation for a specific property
  51750. * @param property defines the propertyu to look for
  51751. * @returns null or the source animation for the given property
  51752. */
  51753. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51754. var runtimeAnimations = this._runtimeAnimations;
  51755. for (var index = 0; index < runtimeAnimations.length; index++) {
  51756. if (runtimeAnimations[index].animation.targetProperty === property) {
  51757. return runtimeAnimations[index].animation;
  51758. }
  51759. }
  51760. return null;
  51761. };
  51762. /**
  51763. * Gets the runtime animation for a specific property
  51764. * @param property defines the propertyu to look for
  51765. * @returns null or the runtime animation for the given property
  51766. */
  51767. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51768. var runtimeAnimations = this._runtimeAnimations;
  51769. for (var index = 0; index < runtimeAnimations.length; index++) {
  51770. if (runtimeAnimations[index].animation.targetProperty === property) {
  51771. return runtimeAnimations[index];
  51772. }
  51773. }
  51774. return null;
  51775. };
  51776. /**
  51777. * Resets the animatable to its original state
  51778. */
  51779. Animatable.prototype.reset = function () {
  51780. var runtimeAnimations = this._runtimeAnimations;
  51781. for (var index = 0; index < runtimeAnimations.length; index++) {
  51782. runtimeAnimations[index].reset(true);
  51783. }
  51784. this._localDelayOffset = null;
  51785. this._pausedDelay = null;
  51786. };
  51787. /**
  51788. * Allows the animatable to blend with current running animations
  51789. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51790. * @param blendingSpeed defines the blending speed to use
  51791. */
  51792. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51793. var runtimeAnimations = this._runtimeAnimations;
  51794. for (var index = 0; index < runtimeAnimations.length; index++) {
  51795. runtimeAnimations[index].animation.enableBlending = true;
  51796. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51797. }
  51798. };
  51799. /**
  51800. * Disable animation blending
  51801. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51802. */
  51803. Animatable.prototype.disableBlending = function () {
  51804. var runtimeAnimations = this._runtimeAnimations;
  51805. for (var index = 0; index < runtimeAnimations.length; index++) {
  51806. runtimeAnimations[index].animation.enableBlending = false;
  51807. }
  51808. };
  51809. /**
  51810. * Jump directly to a given frame
  51811. * @param frame defines the frame to jump to
  51812. */
  51813. Animatable.prototype.goToFrame = function (frame) {
  51814. var runtimeAnimations = this._runtimeAnimations;
  51815. if (runtimeAnimations[0]) {
  51816. var fps = runtimeAnimations[0].animation.framePerSecond;
  51817. var currentFrame = runtimeAnimations[0].currentFrame;
  51818. var adjustTime = frame - currentFrame;
  51819. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51820. if (this._localDelayOffset === null) {
  51821. this._localDelayOffset = 0;
  51822. }
  51823. this._localDelayOffset -= delay;
  51824. }
  51825. for (var index = 0; index < runtimeAnimations.length; index++) {
  51826. runtimeAnimations[index].goToFrame(frame);
  51827. }
  51828. };
  51829. /**
  51830. * Pause the animation
  51831. */
  51832. Animatable.prototype.pause = function () {
  51833. if (this._paused) {
  51834. return;
  51835. }
  51836. this._paused = true;
  51837. };
  51838. /**
  51839. * Restart the animation
  51840. */
  51841. Animatable.prototype.restart = function () {
  51842. this._paused = false;
  51843. };
  51844. Animatable.prototype._raiseOnAnimationEnd = function () {
  51845. if (this.onAnimationEnd) {
  51846. this.onAnimationEnd();
  51847. }
  51848. this.onAnimationEndObservable.notifyObservers(this);
  51849. };
  51850. /**
  51851. * Stop and delete the current animation
  51852. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51853. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51854. */
  51855. Animatable.prototype.stop = function (animationName, targetMask) {
  51856. if (animationName || targetMask) {
  51857. var idx = this._scene._activeAnimatables.indexOf(this);
  51858. if (idx > -1) {
  51859. var runtimeAnimations = this._runtimeAnimations;
  51860. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51861. var runtimeAnimation = runtimeAnimations[index];
  51862. if (animationName && runtimeAnimation.animation.name != animationName) {
  51863. continue;
  51864. }
  51865. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51866. continue;
  51867. }
  51868. runtimeAnimation.dispose();
  51869. runtimeAnimations.splice(index, 1);
  51870. }
  51871. if (runtimeAnimations.length == 0) {
  51872. this._scene._activeAnimatables.splice(idx, 1);
  51873. this._raiseOnAnimationEnd();
  51874. }
  51875. }
  51876. }
  51877. else {
  51878. var index = this._scene._activeAnimatables.indexOf(this);
  51879. if (index > -1) {
  51880. this._scene._activeAnimatables.splice(index, 1);
  51881. var runtimeAnimations = this._runtimeAnimations;
  51882. for (var index = 0; index < runtimeAnimations.length; index++) {
  51883. runtimeAnimations[index].dispose();
  51884. }
  51885. this._raiseOnAnimationEnd();
  51886. }
  51887. }
  51888. };
  51889. /**
  51890. * Wait asynchronously for the animation to end
  51891. * @returns a promise which will be fullfilled when the animation ends
  51892. */
  51893. Animatable.prototype.waitAsync = function () {
  51894. var _this = this;
  51895. return new Promise(function (resolve, reject) {
  51896. _this.onAnimationEndObservable.add(function () {
  51897. resolve(_this);
  51898. }, undefined, undefined, _this, true);
  51899. });
  51900. };
  51901. /** @hidden */
  51902. Animatable.prototype._animate = function (delay) {
  51903. if (this._paused) {
  51904. this.animationStarted = false;
  51905. if (this._pausedDelay === null) {
  51906. this._pausedDelay = delay;
  51907. }
  51908. return true;
  51909. }
  51910. if (this._localDelayOffset === null) {
  51911. this._localDelayOffset = delay;
  51912. this._pausedDelay = null;
  51913. }
  51914. else if (this._pausedDelay !== null) {
  51915. this._localDelayOffset += delay - this._pausedDelay;
  51916. this._pausedDelay = null;
  51917. }
  51918. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51919. return true;
  51920. }
  51921. // Animating
  51922. var running = false;
  51923. var runtimeAnimations = this._runtimeAnimations;
  51924. var index;
  51925. for (index = 0; index < runtimeAnimations.length; index++) {
  51926. var animation = runtimeAnimations[index];
  51927. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51928. running = running || isRunning;
  51929. }
  51930. this.animationStarted = running;
  51931. if (!running) {
  51932. if (this.disposeOnEnd) {
  51933. // Remove from active animatables
  51934. index = this._scene._activeAnimatables.indexOf(this);
  51935. this._scene._activeAnimatables.splice(index, 1);
  51936. // Dispose all runtime animations
  51937. for (index = 0; index < runtimeAnimations.length; index++) {
  51938. runtimeAnimations[index].dispose();
  51939. }
  51940. }
  51941. this._raiseOnAnimationEnd();
  51942. if (this.disposeOnEnd) {
  51943. this.onAnimationEnd = null;
  51944. this.onAnimationEndObservable.clear();
  51945. }
  51946. }
  51947. return running;
  51948. };
  51949. return Animatable;
  51950. }());
  51951. BABYLON.Animatable = Animatable;
  51952. })(BABYLON || (BABYLON = {}));
  51953. //# sourceMappingURL=babylon.animatable.js.map
  51954. var BABYLON;
  51955. (function (BABYLON) {
  51956. var EasingFunction = /** @class */ (function () {
  51957. function EasingFunction() {
  51958. // Properties
  51959. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51960. }
  51961. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51962. get: function () {
  51963. return EasingFunction._EASINGMODE_EASEIN;
  51964. },
  51965. enumerable: true,
  51966. configurable: true
  51967. });
  51968. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51969. get: function () {
  51970. return EasingFunction._EASINGMODE_EASEOUT;
  51971. },
  51972. enumerable: true,
  51973. configurable: true
  51974. });
  51975. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51976. get: function () {
  51977. return EasingFunction._EASINGMODE_EASEINOUT;
  51978. },
  51979. enumerable: true,
  51980. configurable: true
  51981. });
  51982. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51983. var n = Math.min(Math.max(easingMode, 0), 2);
  51984. this._easingMode = n;
  51985. };
  51986. EasingFunction.prototype.getEasingMode = function () {
  51987. return this._easingMode;
  51988. };
  51989. EasingFunction.prototype.easeInCore = function (gradient) {
  51990. throw new Error('You must implement this method');
  51991. };
  51992. EasingFunction.prototype.ease = function (gradient) {
  51993. switch (this._easingMode) {
  51994. case EasingFunction.EASINGMODE_EASEIN:
  51995. return this.easeInCore(gradient);
  51996. case EasingFunction.EASINGMODE_EASEOUT:
  51997. return (1 - this.easeInCore(1 - gradient));
  51998. }
  51999. if (gradient >= 0.5) {
  52000. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52001. }
  52002. return (this.easeInCore(gradient * 2) * 0.5);
  52003. };
  52004. //Statics
  52005. EasingFunction._EASINGMODE_EASEIN = 0;
  52006. EasingFunction._EASINGMODE_EASEOUT = 1;
  52007. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52008. return EasingFunction;
  52009. }());
  52010. BABYLON.EasingFunction = EasingFunction;
  52011. var CircleEase = /** @class */ (function (_super) {
  52012. __extends(CircleEase, _super);
  52013. function CircleEase() {
  52014. return _super !== null && _super.apply(this, arguments) || this;
  52015. }
  52016. CircleEase.prototype.easeInCore = function (gradient) {
  52017. gradient = Math.max(0, Math.min(1, gradient));
  52018. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52019. };
  52020. return CircleEase;
  52021. }(EasingFunction));
  52022. BABYLON.CircleEase = CircleEase;
  52023. var BackEase = /** @class */ (function (_super) {
  52024. __extends(BackEase, _super);
  52025. function BackEase(amplitude) {
  52026. if (amplitude === void 0) { amplitude = 1; }
  52027. var _this = _super.call(this) || this;
  52028. _this.amplitude = amplitude;
  52029. return _this;
  52030. }
  52031. BackEase.prototype.easeInCore = function (gradient) {
  52032. var num = Math.max(0, this.amplitude);
  52033. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52034. };
  52035. return BackEase;
  52036. }(EasingFunction));
  52037. BABYLON.BackEase = BackEase;
  52038. var BounceEase = /** @class */ (function (_super) {
  52039. __extends(BounceEase, _super);
  52040. function BounceEase(bounces, bounciness) {
  52041. if (bounces === void 0) { bounces = 3; }
  52042. if (bounciness === void 0) { bounciness = 2; }
  52043. var _this = _super.call(this) || this;
  52044. _this.bounces = bounces;
  52045. _this.bounciness = bounciness;
  52046. return _this;
  52047. }
  52048. BounceEase.prototype.easeInCore = function (gradient) {
  52049. var y = Math.max(0.0, this.bounces);
  52050. var bounciness = this.bounciness;
  52051. if (bounciness <= 1.0) {
  52052. bounciness = 1.001;
  52053. }
  52054. var num9 = Math.pow(bounciness, y);
  52055. var num5 = 1.0 - bounciness;
  52056. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52057. var num15 = gradient * num4;
  52058. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52059. var num3 = Math.floor(num65);
  52060. var num13 = num3 + 1.0;
  52061. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52062. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52063. var num7 = (num8 + num12) * 0.5;
  52064. var num6 = gradient - num7;
  52065. var num2 = num7 - num8;
  52066. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52067. };
  52068. return BounceEase;
  52069. }(EasingFunction));
  52070. BABYLON.BounceEase = BounceEase;
  52071. var CubicEase = /** @class */ (function (_super) {
  52072. __extends(CubicEase, _super);
  52073. function CubicEase() {
  52074. return _super !== null && _super.apply(this, arguments) || this;
  52075. }
  52076. CubicEase.prototype.easeInCore = function (gradient) {
  52077. return (gradient * gradient * gradient);
  52078. };
  52079. return CubicEase;
  52080. }(EasingFunction));
  52081. BABYLON.CubicEase = CubicEase;
  52082. var ElasticEase = /** @class */ (function (_super) {
  52083. __extends(ElasticEase, _super);
  52084. function ElasticEase(oscillations, springiness) {
  52085. if (oscillations === void 0) { oscillations = 3; }
  52086. if (springiness === void 0) { springiness = 3; }
  52087. var _this = _super.call(this) || this;
  52088. _this.oscillations = oscillations;
  52089. _this.springiness = springiness;
  52090. return _this;
  52091. }
  52092. ElasticEase.prototype.easeInCore = function (gradient) {
  52093. var num2;
  52094. var num3 = Math.max(0.0, this.oscillations);
  52095. var num = Math.max(0.0, this.springiness);
  52096. if (num == 0) {
  52097. num2 = gradient;
  52098. }
  52099. else {
  52100. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52101. }
  52102. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52103. };
  52104. return ElasticEase;
  52105. }(EasingFunction));
  52106. BABYLON.ElasticEase = ElasticEase;
  52107. var ExponentialEase = /** @class */ (function (_super) {
  52108. __extends(ExponentialEase, _super);
  52109. function ExponentialEase(exponent) {
  52110. if (exponent === void 0) { exponent = 2; }
  52111. var _this = _super.call(this) || this;
  52112. _this.exponent = exponent;
  52113. return _this;
  52114. }
  52115. ExponentialEase.prototype.easeInCore = function (gradient) {
  52116. if (this.exponent <= 0) {
  52117. return gradient;
  52118. }
  52119. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52120. };
  52121. return ExponentialEase;
  52122. }(EasingFunction));
  52123. BABYLON.ExponentialEase = ExponentialEase;
  52124. var PowerEase = /** @class */ (function (_super) {
  52125. __extends(PowerEase, _super);
  52126. function PowerEase(power) {
  52127. if (power === void 0) { power = 2; }
  52128. var _this = _super.call(this) || this;
  52129. _this.power = power;
  52130. return _this;
  52131. }
  52132. PowerEase.prototype.easeInCore = function (gradient) {
  52133. var y = Math.max(0.0, this.power);
  52134. return Math.pow(gradient, y);
  52135. };
  52136. return PowerEase;
  52137. }(EasingFunction));
  52138. BABYLON.PowerEase = PowerEase;
  52139. var QuadraticEase = /** @class */ (function (_super) {
  52140. __extends(QuadraticEase, _super);
  52141. function QuadraticEase() {
  52142. return _super !== null && _super.apply(this, arguments) || this;
  52143. }
  52144. QuadraticEase.prototype.easeInCore = function (gradient) {
  52145. return (gradient * gradient);
  52146. };
  52147. return QuadraticEase;
  52148. }(EasingFunction));
  52149. BABYLON.QuadraticEase = QuadraticEase;
  52150. var QuarticEase = /** @class */ (function (_super) {
  52151. __extends(QuarticEase, _super);
  52152. function QuarticEase() {
  52153. return _super !== null && _super.apply(this, arguments) || this;
  52154. }
  52155. QuarticEase.prototype.easeInCore = function (gradient) {
  52156. return (gradient * gradient * gradient * gradient);
  52157. };
  52158. return QuarticEase;
  52159. }(EasingFunction));
  52160. BABYLON.QuarticEase = QuarticEase;
  52161. var QuinticEase = /** @class */ (function (_super) {
  52162. __extends(QuinticEase, _super);
  52163. function QuinticEase() {
  52164. return _super !== null && _super.apply(this, arguments) || this;
  52165. }
  52166. QuinticEase.prototype.easeInCore = function (gradient) {
  52167. return (gradient * gradient * gradient * gradient * gradient);
  52168. };
  52169. return QuinticEase;
  52170. }(EasingFunction));
  52171. BABYLON.QuinticEase = QuinticEase;
  52172. var SineEase = /** @class */ (function (_super) {
  52173. __extends(SineEase, _super);
  52174. function SineEase() {
  52175. return _super !== null && _super.apply(this, arguments) || this;
  52176. }
  52177. SineEase.prototype.easeInCore = function (gradient) {
  52178. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52179. };
  52180. return SineEase;
  52181. }(EasingFunction));
  52182. BABYLON.SineEase = SineEase;
  52183. var BezierCurveEase = /** @class */ (function (_super) {
  52184. __extends(BezierCurveEase, _super);
  52185. function BezierCurveEase(x1, y1, x2, y2) {
  52186. if (x1 === void 0) { x1 = 0; }
  52187. if (y1 === void 0) { y1 = 0; }
  52188. if (x2 === void 0) { x2 = 1; }
  52189. if (y2 === void 0) { y2 = 1; }
  52190. var _this = _super.call(this) || this;
  52191. _this.x1 = x1;
  52192. _this.y1 = y1;
  52193. _this.x2 = x2;
  52194. _this.y2 = y2;
  52195. return _this;
  52196. }
  52197. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52198. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52199. };
  52200. return BezierCurveEase;
  52201. }(EasingFunction));
  52202. BABYLON.BezierCurveEase = BezierCurveEase;
  52203. })(BABYLON || (BABYLON = {}));
  52204. //# sourceMappingURL=babylon.easing.js.map
  52205. var BABYLON;
  52206. (function (BABYLON) {
  52207. /**
  52208. * A Condition applied to an Action
  52209. */
  52210. var Condition = /** @class */ (function () {
  52211. /**
  52212. * Creates a new Condition
  52213. * @param actionManager the manager of the action the condition is applied to
  52214. */
  52215. function Condition(actionManager) {
  52216. this._actionManager = actionManager;
  52217. }
  52218. /**
  52219. * Check if the current condition is valid
  52220. * @returns a boolean
  52221. */
  52222. Condition.prototype.isValid = function () {
  52223. return true;
  52224. };
  52225. /**
  52226. * Internal only
  52227. * @hidden
  52228. */
  52229. Condition.prototype._getProperty = function (propertyPath) {
  52230. return this._actionManager._getProperty(propertyPath);
  52231. };
  52232. /**
  52233. * Internal only
  52234. * @hidden
  52235. */
  52236. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52237. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52238. };
  52239. /**
  52240. * Serialize placeholder for child classes
  52241. * @returns the serialized object
  52242. */
  52243. Condition.prototype.serialize = function () {
  52244. };
  52245. /**
  52246. * Internal only
  52247. * @hidden
  52248. */
  52249. Condition.prototype._serialize = function (serializedCondition) {
  52250. return {
  52251. type: 2,
  52252. children: [],
  52253. name: serializedCondition.name,
  52254. properties: serializedCondition.properties
  52255. };
  52256. };
  52257. return Condition;
  52258. }());
  52259. BABYLON.Condition = Condition;
  52260. /**
  52261. * Defines specific conditional operators as extensions of Condition
  52262. */
  52263. var ValueCondition = /** @class */ (function (_super) {
  52264. __extends(ValueCondition, _super);
  52265. /**
  52266. * Creates a new ValueCondition
  52267. * @param actionManager manager for the action the condition applies to
  52268. * @param target for the action
  52269. * @param propertyPath path to specify the property of the target the conditional operator uses
  52270. * @param value the value compared by the conditional operator against the current value of the property
  52271. * @param operator the conditional operator, default ValueCondition.IsEqual
  52272. */
  52273. function ValueCondition(actionManager, target,
  52274. /** path to specify the property of the target the conditional operator uses */
  52275. propertyPath,
  52276. /** the value compared by the conditional operator against the current value of the property */
  52277. value,
  52278. /** the conditional operator, default ValueCondition.IsEqual */
  52279. operator) {
  52280. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52281. var _this = _super.call(this, actionManager) || this;
  52282. _this.propertyPath = propertyPath;
  52283. _this.value = value;
  52284. _this.operator = operator;
  52285. _this._target = target;
  52286. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52287. _this._property = _this._getProperty(_this.propertyPath);
  52288. return _this;
  52289. }
  52290. Object.defineProperty(ValueCondition, "IsEqual", {
  52291. /**
  52292. * returns the number for IsEqual
  52293. */
  52294. get: function () {
  52295. return ValueCondition._IsEqual;
  52296. },
  52297. enumerable: true,
  52298. configurable: true
  52299. });
  52300. Object.defineProperty(ValueCondition, "IsDifferent", {
  52301. /**
  52302. * Returns the number for IsDifferent
  52303. */
  52304. get: function () {
  52305. return ValueCondition._IsDifferent;
  52306. },
  52307. enumerable: true,
  52308. configurable: true
  52309. });
  52310. Object.defineProperty(ValueCondition, "IsGreater", {
  52311. /**
  52312. * Returns the number for IsGreater
  52313. */
  52314. get: function () {
  52315. return ValueCondition._IsGreater;
  52316. },
  52317. enumerable: true,
  52318. configurable: true
  52319. });
  52320. Object.defineProperty(ValueCondition, "IsLesser", {
  52321. /**
  52322. * Returns the number for IsLesser
  52323. */
  52324. get: function () {
  52325. return ValueCondition._IsLesser;
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. /**
  52331. * Compares the given value with the property value for the specified conditional operator
  52332. * @returns the result of the comparison
  52333. */
  52334. ValueCondition.prototype.isValid = function () {
  52335. switch (this.operator) {
  52336. case ValueCondition.IsGreater:
  52337. return this._effectiveTarget[this._property] > this.value;
  52338. case ValueCondition.IsLesser:
  52339. return this._effectiveTarget[this._property] < this.value;
  52340. case ValueCondition.IsEqual:
  52341. case ValueCondition.IsDifferent:
  52342. var check;
  52343. if (this.value.equals) {
  52344. check = this.value.equals(this._effectiveTarget[this._property]);
  52345. }
  52346. else {
  52347. check = this.value === this._effectiveTarget[this._property];
  52348. }
  52349. return this.operator === ValueCondition.IsEqual ? check : !check;
  52350. }
  52351. return false;
  52352. };
  52353. /**
  52354. * Serialize the ValueCondition into a JSON compatible object
  52355. * @returns serialization object
  52356. */
  52357. ValueCondition.prototype.serialize = function () {
  52358. return this._serialize({
  52359. name: "ValueCondition",
  52360. properties: [
  52361. BABYLON.Action._GetTargetProperty(this._target),
  52362. { name: "propertyPath", value: this.propertyPath },
  52363. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52364. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52365. ]
  52366. });
  52367. };
  52368. /**
  52369. * Gets the name of the conditional operator for the ValueCondition
  52370. * @param operator the conditional operator
  52371. * @returns the name
  52372. */
  52373. ValueCondition.GetOperatorName = function (operator) {
  52374. switch (operator) {
  52375. case ValueCondition._IsEqual: return "IsEqual";
  52376. case ValueCondition._IsDifferent: return "IsDifferent";
  52377. case ValueCondition._IsGreater: return "IsGreater";
  52378. case ValueCondition._IsLesser: return "IsLesser";
  52379. default: return "";
  52380. }
  52381. };
  52382. /**
  52383. * Internal only
  52384. * @hidden
  52385. */
  52386. ValueCondition._IsEqual = 0;
  52387. /**
  52388. * Internal only
  52389. * @hidden
  52390. */
  52391. ValueCondition._IsDifferent = 1;
  52392. /**
  52393. * Internal only
  52394. * @hidden
  52395. */
  52396. ValueCondition._IsGreater = 2;
  52397. /**
  52398. * Internal only
  52399. * @hidden
  52400. */
  52401. ValueCondition._IsLesser = 3;
  52402. return ValueCondition;
  52403. }(Condition));
  52404. BABYLON.ValueCondition = ValueCondition;
  52405. /**
  52406. * Defines a predicate condition as an extension of Condition
  52407. */
  52408. var PredicateCondition = /** @class */ (function (_super) {
  52409. __extends(PredicateCondition, _super);
  52410. /**
  52411. * Creates a new PredicateCondition
  52412. * @param actionManager manager for the action the condition applies to
  52413. * @param predicate defines the predicate function used to validate the condition
  52414. */
  52415. function PredicateCondition(actionManager,
  52416. /** defines the predicate function used to validate the condition */
  52417. predicate) {
  52418. var _this = _super.call(this, actionManager) || this;
  52419. _this.predicate = predicate;
  52420. return _this;
  52421. }
  52422. /**
  52423. * @returns the validity of the predicate condition
  52424. */
  52425. PredicateCondition.prototype.isValid = function () {
  52426. return this.predicate();
  52427. };
  52428. return PredicateCondition;
  52429. }(Condition));
  52430. BABYLON.PredicateCondition = PredicateCondition;
  52431. /**
  52432. * Defines a state condition as an extension of Condition
  52433. */
  52434. var StateCondition = /** @class */ (function (_super) {
  52435. __extends(StateCondition, _super);
  52436. /**
  52437. * Creates a new StateCondition
  52438. * @param actionManager manager for the action the condition applies to
  52439. * @param target of the condition
  52440. * @param value to compare with target state
  52441. */
  52442. function StateCondition(actionManager, target, value) {
  52443. var _this = _super.call(this, actionManager) || this;
  52444. _this.value = value;
  52445. _this._target = target;
  52446. return _this;
  52447. }
  52448. /**
  52449. * @returns the validity of the state
  52450. */
  52451. StateCondition.prototype.isValid = function () {
  52452. return this._target.state === this.value;
  52453. };
  52454. /**
  52455. * Serialize the StateCondition into a JSON compatible object
  52456. * @returns serialization object
  52457. */
  52458. StateCondition.prototype.serialize = function () {
  52459. return this._serialize({
  52460. name: "StateCondition",
  52461. properties: [
  52462. BABYLON.Action._GetTargetProperty(this._target),
  52463. { name: "value", value: this.value }
  52464. ]
  52465. });
  52466. };
  52467. return StateCondition;
  52468. }(Condition));
  52469. BABYLON.StateCondition = StateCondition;
  52470. })(BABYLON || (BABYLON = {}));
  52471. //# sourceMappingURL=babylon.condition.js.map
  52472. var BABYLON;
  52473. (function (BABYLON) {
  52474. /**
  52475. * The action to be carried out following a trigger
  52476. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52477. */
  52478. var Action = /** @class */ (function () {
  52479. /**
  52480. * Creates a new Action
  52481. * @param triggerOptions the trigger, with or without parameters, for the action
  52482. * @param condition an optional determinant of action
  52483. */
  52484. function Action(
  52485. /** the trigger, with or without parameters, for the action */
  52486. triggerOptions, condition) {
  52487. this.triggerOptions = triggerOptions;
  52488. /**
  52489. * An event triggered prior to action being executed.
  52490. */
  52491. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52492. if (triggerOptions.parameter) {
  52493. this.trigger = triggerOptions.trigger;
  52494. this._triggerParameter = triggerOptions.parameter;
  52495. }
  52496. else if (triggerOptions.trigger) {
  52497. this.trigger = triggerOptions.trigger;
  52498. }
  52499. else {
  52500. this.trigger = triggerOptions;
  52501. }
  52502. this._nextActiveAction = this;
  52503. this._condition = condition;
  52504. }
  52505. /**
  52506. * Internal only
  52507. * @hidden
  52508. */
  52509. Action.prototype._prepare = function () {
  52510. };
  52511. /**
  52512. * Gets the trigger parameters
  52513. * @returns the trigger parameters
  52514. */
  52515. Action.prototype.getTriggerParameter = function () {
  52516. return this._triggerParameter;
  52517. };
  52518. /**
  52519. * Internal only - executes current action event
  52520. * @hidden
  52521. */
  52522. Action.prototype._executeCurrent = function (evt) {
  52523. if (this._nextActiveAction._condition) {
  52524. var condition = this._nextActiveAction._condition;
  52525. var currentRenderId = this._actionManager.getScene().getRenderId();
  52526. // We cache the current evaluation for the current frame
  52527. if (condition._evaluationId === currentRenderId) {
  52528. if (!condition._currentResult) {
  52529. return;
  52530. }
  52531. }
  52532. else {
  52533. condition._evaluationId = currentRenderId;
  52534. if (!condition.isValid()) {
  52535. condition._currentResult = false;
  52536. return;
  52537. }
  52538. condition._currentResult = true;
  52539. }
  52540. }
  52541. this.onBeforeExecuteObservable.notifyObservers(this);
  52542. this._nextActiveAction.execute(evt);
  52543. this.skipToNextActiveAction();
  52544. };
  52545. /**
  52546. * Execute placeholder for child classes
  52547. * @param evt optional action event
  52548. */
  52549. Action.prototype.execute = function (evt) {
  52550. };
  52551. /**
  52552. * Skips to next active action
  52553. */
  52554. Action.prototype.skipToNextActiveAction = function () {
  52555. if (this._nextActiveAction._child) {
  52556. if (!this._nextActiveAction._child._actionManager) {
  52557. this._nextActiveAction._child._actionManager = this._actionManager;
  52558. }
  52559. this._nextActiveAction = this._nextActiveAction._child;
  52560. }
  52561. else {
  52562. this._nextActiveAction = this;
  52563. }
  52564. };
  52565. /**
  52566. * Adds action to chain of actions, may be a DoNothingAction
  52567. * @param action defines the next action to execute
  52568. * @returns The action passed in
  52569. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52570. */
  52571. Action.prototype.then = function (action) {
  52572. this._child = action;
  52573. action._actionManager = this._actionManager;
  52574. action._prepare();
  52575. return action;
  52576. };
  52577. /**
  52578. * Internal only
  52579. * @hidden
  52580. */
  52581. Action.prototype._getProperty = function (propertyPath) {
  52582. return this._actionManager._getProperty(propertyPath);
  52583. };
  52584. /**
  52585. * Internal only
  52586. * @hidden
  52587. */
  52588. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52589. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52590. };
  52591. /**
  52592. * Serialize placeholder for child classes
  52593. * @param parent of child
  52594. * @returns the serialized object
  52595. */
  52596. Action.prototype.serialize = function (parent) {
  52597. };
  52598. /**
  52599. * Internal only called by serialize
  52600. * @hidden
  52601. */
  52602. Action.prototype._serialize = function (serializedAction, parent) {
  52603. var serializationObject = {
  52604. type: 1,
  52605. children: [],
  52606. name: serializedAction.name,
  52607. properties: serializedAction.properties || []
  52608. };
  52609. // Serialize child
  52610. if (this._child) {
  52611. this._child.serialize(serializationObject);
  52612. }
  52613. // Check if "this" has a condition
  52614. if (this._condition) {
  52615. var serializedCondition = this._condition.serialize();
  52616. serializedCondition.children.push(serializationObject);
  52617. if (parent) {
  52618. parent.children.push(serializedCondition);
  52619. }
  52620. return serializedCondition;
  52621. }
  52622. if (parent) {
  52623. parent.children.push(serializationObject);
  52624. }
  52625. return serializationObject;
  52626. };
  52627. /**
  52628. * Internal only
  52629. * @hidden
  52630. */
  52631. Action._SerializeValueAsString = function (value) {
  52632. if (typeof value === "number") {
  52633. return value.toString();
  52634. }
  52635. if (typeof value === "boolean") {
  52636. return value ? "true" : "false";
  52637. }
  52638. if (value instanceof BABYLON.Vector2) {
  52639. return value.x + ", " + value.y;
  52640. }
  52641. if (value instanceof BABYLON.Vector3) {
  52642. return value.x + ", " + value.y + ", " + value.z;
  52643. }
  52644. if (value instanceof BABYLON.Color3) {
  52645. return value.r + ", " + value.g + ", " + value.b;
  52646. }
  52647. if (value instanceof BABYLON.Color4) {
  52648. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52649. }
  52650. return value; // string
  52651. };
  52652. /**
  52653. * Internal only
  52654. * @hidden
  52655. */
  52656. Action._GetTargetProperty = function (target) {
  52657. return {
  52658. name: "target",
  52659. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52660. : target instanceof BABYLON.Light ? "LightProperties"
  52661. : target instanceof BABYLON.Camera ? "CameraProperties"
  52662. : "SceneProperties",
  52663. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52664. };
  52665. };
  52666. return Action;
  52667. }());
  52668. BABYLON.Action = Action;
  52669. })(BABYLON || (BABYLON = {}));
  52670. //# sourceMappingURL=babylon.action.js.map
  52671. var BABYLON;
  52672. (function (BABYLON) {
  52673. /**
  52674. * ActionEvent is the event being sent when an action is triggered.
  52675. */
  52676. var ActionEvent = /** @class */ (function () {
  52677. /**
  52678. * Creates a new ActionEvent
  52679. * @param source The mesh or sprite that triggered the action
  52680. * @param pointerX The X mouse cursor position at the time of the event
  52681. * @param pointerY The Y mouse cursor position at the time of the event
  52682. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52683. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52684. * @param additionalData additional data for the event
  52685. */
  52686. function ActionEvent(
  52687. /** The mesh or sprite that triggered the action */
  52688. source,
  52689. /** The X mouse cursor position at the time of the event */
  52690. pointerX,
  52691. /** The Y mouse cursor position at the time of the event */
  52692. pointerY,
  52693. /** The mesh that is currently pointed at (can be null) */
  52694. meshUnderPointer,
  52695. /** the original (browser) event that triggered the ActionEvent */
  52696. sourceEvent,
  52697. /** additional data for the event */
  52698. additionalData) {
  52699. this.source = source;
  52700. this.pointerX = pointerX;
  52701. this.pointerY = pointerY;
  52702. this.meshUnderPointer = meshUnderPointer;
  52703. this.sourceEvent = sourceEvent;
  52704. this.additionalData = additionalData;
  52705. }
  52706. /**
  52707. * Helper function to auto-create an ActionEvent from a source mesh.
  52708. * @param source The source mesh that triggered the event
  52709. * @param evt The original (browser) event
  52710. * @param additionalData additional data for the event
  52711. * @returns the new ActionEvent
  52712. */
  52713. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52714. var scene = source.getScene();
  52715. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52716. };
  52717. /**
  52718. * Helper function to auto-create an ActionEvent from a source sprite
  52719. * @param source The source sprite that triggered the event
  52720. * @param scene Scene associated with the sprite
  52721. * @param evt The original (browser) event
  52722. * @param additionalData additional data for the event
  52723. * @returns the new ActionEvent
  52724. */
  52725. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52726. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52727. };
  52728. /**
  52729. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52730. * @param scene the scene where the event occurred
  52731. * @param evt The original (browser) event
  52732. * @returns the new ActionEvent
  52733. */
  52734. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52735. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52736. };
  52737. /**
  52738. * Helper function to auto-create an ActionEvent from a primitive
  52739. * @param prim defines the target primitive
  52740. * @param pointerPos defines the pointer position
  52741. * @param evt The original (browser) event
  52742. * @param additionalData additional data for the event
  52743. * @returns the new ActionEvent
  52744. */
  52745. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52746. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52747. };
  52748. return ActionEvent;
  52749. }());
  52750. BABYLON.ActionEvent = ActionEvent;
  52751. /**
  52752. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52753. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52754. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52755. */
  52756. var ActionManager = /** @class */ (function () {
  52757. /**
  52758. * Creates a new action manager
  52759. * @param scene defines the hosting scene
  52760. */
  52761. function ActionManager(scene) {
  52762. // Members
  52763. /** Gets the list of actions */
  52764. this.actions = new Array();
  52765. /** Gets the cursor to use when hovering items */
  52766. this.hoverCursor = '';
  52767. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52768. scene.actionManagers.push(this);
  52769. }
  52770. Object.defineProperty(ActionManager, "NothingTrigger", {
  52771. /**
  52772. * Nothing
  52773. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52774. */
  52775. get: function () {
  52776. return ActionManager._NothingTrigger;
  52777. },
  52778. enumerable: true,
  52779. configurable: true
  52780. });
  52781. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52782. /**
  52783. * On pick
  52784. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52785. */
  52786. get: function () {
  52787. return ActionManager._OnPickTrigger;
  52788. },
  52789. enumerable: true,
  52790. configurable: true
  52791. });
  52792. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52793. /**
  52794. * On left pick
  52795. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52796. */
  52797. get: function () {
  52798. return ActionManager._OnLeftPickTrigger;
  52799. },
  52800. enumerable: true,
  52801. configurable: true
  52802. });
  52803. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52804. /**
  52805. * On right pick
  52806. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52807. */
  52808. get: function () {
  52809. return ActionManager._OnRightPickTrigger;
  52810. },
  52811. enumerable: true,
  52812. configurable: true
  52813. });
  52814. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52815. /**
  52816. * On center pick
  52817. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52818. */
  52819. get: function () {
  52820. return ActionManager._OnCenterPickTrigger;
  52821. },
  52822. enumerable: true,
  52823. configurable: true
  52824. });
  52825. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52826. /**
  52827. * On pick down
  52828. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52829. */
  52830. get: function () {
  52831. return ActionManager._OnPickDownTrigger;
  52832. },
  52833. enumerable: true,
  52834. configurable: true
  52835. });
  52836. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52837. /**
  52838. * On double pick
  52839. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52840. */
  52841. get: function () {
  52842. return ActionManager._OnDoublePickTrigger;
  52843. },
  52844. enumerable: true,
  52845. configurable: true
  52846. });
  52847. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52848. /**
  52849. * On pick up
  52850. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52851. */
  52852. get: function () {
  52853. return ActionManager._OnPickUpTrigger;
  52854. },
  52855. enumerable: true,
  52856. configurable: true
  52857. });
  52858. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52859. /**
  52860. * On pick out.
  52861. * This trigger will only be raised if you also declared a OnPickDown
  52862. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52863. */
  52864. get: function () {
  52865. return ActionManager._OnPickOutTrigger;
  52866. },
  52867. enumerable: true,
  52868. configurable: true
  52869. });
  52870. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52871. /**
  52872. * On long press
  52873. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52874. */
  52875. get: function () {
  52876. return ActionManager._OnLongPressTrigger;
  52877. },
  52878. enumerable: true,
  52879. configurable: true
  52880. });
  52881. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52882. /**
  52883. * On pointer over
  52884. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52885. */
  52886. get: function () {
  52887. return ActionManager._OnPointerOverTrigger;
  52888. },
  52889. enumerable: true,
  52890. configurable: true
  52891. });
  52892. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52893. /**
  52894. * On pointer out
  52895. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52896. */
  52897. get: function () {
  52898. return ActionManager._OnPointerOutTrigger;
  52899. },
  52900. enumerable: true,
  52901. configurable: true
  52902. });
  52903. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52904. /**
  52905. * On every frame
  52906. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52907. */
  52908. get: function () {
  52909. return ActionManager._OnEveryFrameTrigger;
  52910. },
  52911. enumerable: true,
  52912. configurable: true
  52913. });
  52914. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52915. /**
  52916. * On intersection enter
  52917. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52918. */
  52919. get: function () {
  52920. return ActionManager._OnIntersectionEnterTrigger;
  52921. },
  52922. enumerable: true,
  52923. configurable: true
  52924. });
  52925. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52926. /**
  52927. * On intersection exit
  52928. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52929. */
  52930. get: function () {
  52931. return ActionManager._OnIntersectionExitTrigger;
  52932. },
  52933. enumerable: true,
  52934. configurable: true
  52935. });
  52936. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52937. /**
  52938. * On key down
  52939. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52940. */
  52941. get: function () {
  52942. return ActionManager._OnKeyDownTrigger;
  52943. },
  52944. enumerable: true,
  52945. configurable: true
  52946. });
  52947. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52948. /**
  52949. * On key up
  52950. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52951. */
  52952. get: function () {
  52953. return ActionManager._OnKeyUpTrigger;
  52954. },
  52955. enumerable: true,
  52956. configurable: true
  52957. });
  52958. // Methods
  52959. /**
  52960. * Releases all associated resources
  52961. */
  52962. ActionManager.prototype.dispose = function () {
  52963. var index = this._scene.actionManagers.indexOf(this);
  52964. for (var i = 0; i < this.actions.length; i++) {
  52965. var action = this.actions[i];
  52966. ActionManager.Triggers[action.trigger]--;
  52967. if (ActionManager.Triggers[action.trigger] === 0) {
  52968. delete ActionManager.Triggers[action.trigger];
  52969. }
  52970. }
  52971. if (index > -1) {
  52972. this._scene.actionManagers.splice(index, 1);
  52973. }
  52974. };
  52975. /**
  52976. * Gets hosting scene
  52977. * @returns the hosting scene
  52978. */
  52979. ActionManager.prototype.getScene = function () {
  52980. return this._scene;
  52981. };
  52982. /**
  52983. * Does this action manager handles actions of any of the given triggers
  52984. * @param triggers defines the triggers to be tested
  52985. * @return a boolean indicating whether one (or more) of the triggers is handled
  52986. */
  52987. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52988. for (var index = 0; index < this.actions.length; index++) {
  52989. var action = this.actions[index];
  52990. if (triggers.indexOf(action.trigger) > -1) {
  52991. return true;
  52992. }
  52993. }
  52994. return false;
  52995. };
  52996. /**
  52997. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52998. * speed.
  52999. * @param triggerA defines the trigger to be tested
  53000. * @param triggerB defines the trigger to be tested
  53001. * @return a boolean indicating whether one (or more) of the triggers is handled
  53002. */
  53003. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53004. for (var index = 0; index < this.actions.length; index++) {
  53005. var action = this.actions[index];
  53006. if (triggerA == action.trigger || triggerB == action.trigger) {
  53007. return true;
  53008. }
  53009. }
  53010. return false;
  53011. };
  53012. /**
  53013. * Does this action manager handles actions of a given trigger
  53014. * @param trigger defines the trigger to be tested
  53015. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53016. * @return whether the trigger is handled
  53017. */
  53018. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53019. for (var index = 0; index < this.actions.length; index++) {
  53020. var action = this.actions[index];
  53021. if (action.trigger === trigger) {
  53022. if (parameterPredicate) {
  53023. if (parameterPredicate(action.getTriggerParameter())) {
  53024. return true;
  53025. }
  53026. }
  53027. else {
  53028. return true;
  53029. }
  53030. }
  53031. }
  53032. return false;
  53033. };
  53034. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53035. /**
  53036. * Does this action manager has pointer triggers
  53037. */
  53038. get: function () {
  53039. for (var index = 0; index < this.actions.length; index++) {
  53040. var action = this.actions[index];
  53041. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53042. return true;
  53043. }
  53044. }
  53045. return false;
  53046. },
  53047. enumerable: true,
  53048. configurable: true
  53049. });
  53050. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53051. /**
  53052. * Does this action manager has pick triggers
  53053. */
  53054. get: function () {
  53055. for (var index = 0; index < this.actions.length; index++) {
  53056. var action = this.actions[index];
  53057. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53058. return true;
  53059. }
  53060. }
  53061. return false;
  53062. },
  53063. enumerable: true,
  53064. configurable: true
  53065. });
  53066. Object.defineProperty(ActionManager, "HasTriggers", {
  53067. /**
  53068. * Does exist one action manager with at least one trigger
  53069. **/
  53070. get: function () {
  53071. for (var t in ActionManager.Triggers) {
  53072. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53073. return true;
  53074. }
  53075. }
  53076. return false;
  53077. },
  53078. enumerable: true,
  53079. configurable: true
  53080. });
  53081. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53082. /**
  53083. * Does exist one action manager with at least one pick trigger
  53084. **/
  53085. get: function () {
  53086. for (var t in ActionManager.Triggers) {
  53087. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53088. var t_int = parseInt(t);
  53089. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53090. return true;
  53091. }
  53092. }
  53093. }
  53094. return false;
  53095. },
  53096. enumerable: true,
  53097. configurable: true
  53098. });
  53099. /**
  53100. * Does exist one action manager that handles actions of a given trigger
  53101. * @param trigger defines the trigger to be tested
  53102. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53103. **/
  53104. ActionManager.HasSpecificTrigger = function (trigger) {
  53105. for (var t in ActionManager.Triggers) {
  53106. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53107. var t_int = parseInt(t);
  53108. if (t_int === trigger) {
  53109. return true;
  53110. }
  53111. }
  53112. }
  53113. return false;
  53114. };
  53115. /**
  53116. * Registers an action to this action manager
  53117. * @param action defines the action to be registered
  53118. * @return the action amended (prepared) after registration
  53119. */
  53120. ActionManager.prototype.registerAction = function (action) {
  53121. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53122. if (this.getScene().actionManager !== this) {
  53123. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53124. return null;
  53125. }
  53126. }
  53127. this.actions.push(action);
  53128. if (ActionManager.Triggers[action.trigger]) {
  53129. ActionManager.Triggers[action.trigger]++;
  53130. }
  53131. else {
  53132. ActionManager.Triggers[action.trigger] = 1;
  53133. }
  53134. action._actionManager = this;
  53135. action._prepare();
  53136. return action;
  53137. };
  53138. /**
  53139. * Unregisters an action to this action manager
  53140. * @param action defines the action to be unregistered
  53141. * @return a boolean indicating whether the action has been unregistered
  53142. */
  53143. ActionManager.prototype.unregisterAction = function (action) {
  53144. var index = this.actions.indexOf(action);
  53145. if (index !== -1) {
  53146. this.actions.splice(index, 1);
  53147. ActionManager.Triggers[action.trigger] -= 1;
  53148. if (ActionManager.Triggers[action.trigger] === 0) {
  53149. delete ActionManager.Triggers[action.trigger];
  53150. }
  53151. delete action._actionManager;
  53152. return true;
  53153. }
  53154. return false;
  53155. };
  53156. /**
  53157. * Process a specific trigger
  53158. * @param trigger defines the trigger to process
  53159. * @param evt defines the event details to be processed
  53160. */
  53161. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53162. for (var index = 0; index < this.actions.length; index++) {
  53163. var action = this.actions[index];
  53164. if (action.trigger === trigger) {
  53165. if (evt) {
  53166. if (trigger === ActionManager.OnKeyUpTrigger
  53167. || trigger === ActionManager.OnKeyDownTrigger) {
  53168. var parameter = action.getTriggerParameter();
  53169. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53170. if (!parameter.toLowerCase) {
  53171. continue;
  53172. }
  53173. var lowerCase = parameter.toLowerCase();
  53174. if (lowerCase !== evt.sourceEvent.key) {
  53175. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53176. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53177. if (actualkey !== lowerCase) {
  53178. continue;
  53179. }
  53180. }
  53181. }
  53182. }
  53183. }
  53184. action._executeCurrent(evt);
  53185. }
  53186. }
  53187. };
  53188. /** @hidden */
  53189. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53190. var properties = propertyPath.split(".");
  53191. for (var index = 0; index < properties.length - 1; index++) {
  53192. target = target[properties[index]];
  53193. }
  53194. return target;
  53195. };
  53196. /** @hidden */
  53197. ActionManager.prototype._getProperty = function (propertyPath) {
  53198. var properties = propertyPath.split(".");
  53199. return properties[properties.length - 1];
  53200. };
  53201. /**
  53202. * Serialize this manager to a JSON object
  53203. * @param name defines the property name to store this manager
  53204. * @returns a JSON representation of this manager
  53205. */
  53206. ActionManager.prototype.serialize = function (name) {
  53207. var root = {
  53208. children: new Array(),
  53209. name: name,
  53210. type: 3,
  53211. properties: new Array() // Empty for root but required
  53212. };
  53213. for (var i = 0; i < this.actions.length; i++) {
  53214. var triggerObject = {
  53215. type: 0,
  53216. children: new Array(),
  53217. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53218. properties: new Array()
  53219. };
  53220. var triggerOptions = this.actions[i].triggerOptions;
  53221. if (triggerOptions && typeof triggerOptions !== "number") {
  53222. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53223. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53224. }
  53225. else {
  53226. var parameter = {};
  53227. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53228. if (triggerOptions.parameter.mesh) {
  53229. parameter._meshId = triggerOptions.parameter.mesh.id;
  53230. }
  53231. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53232. }
  53233. }
  53234. // Serialize child action, recursively
  53235. this.actions[i].serialize(triggerObject);
  53236. // Add serialized trigger
  53237. root.children.push(triggerObject);
  53238. }
  53239. return root;
  53240. };
  53241. /**
  53242. * Creates a new ActionManager from a JSON data
  53243. * @param parsedActions defines the JSON data to read from
  53244. * @param object defines the hosting mesh
  53245. * @param scene defines the hosting scene
  53246. */
  53247. ActionManager.Parse = function (parsedActions, object, scene) {
  53248. var actionManager = new ActionManager(scene);
  53249. if (object === null)
  53250. scene.actionManager = actionManager;
  53251. else
  53252. object.actionManager = actionManager;
  53253. // instanciate a new object
  53254. var instanciate = function (name, params) {
  53255. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53256. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53257. newInstance.constructor.apply(newInstance, params);
  53258. return newInstance;
  53259. };
  53260. var parseParameter = function (name, value, target, propertyPath) {
  53261. if (propertyPath === null) {
  53262. // String, boolean or float
  53263. var floatValue = parseFloat(value);
  53264. if (value === "true" || value === "false")
  53265. return value === "true";
  53266. else
  53267. return isNaN(floatValue) ? value : floatValue;
  53268. }
  53269. var effectiveTarget = propertyPath.split(".");
  53270. var values = value.split(",");
  53271. // Get effective Target
  53272. for (var i = 0; i < effectiveTarget.length; i++) {
  53273. target = target[effectiveTarget[i]];
  53274. }
  53275. // Return appropriate value with its type
  53276. if (typeof (target) === "boolean")
  53277. return values[0] === "true";
  53278. if (typeof (target) === "string")
  53279. return values[0];
  53280. // Parameters with multiple values such as Vector3 etc.
  53281. var split = new Array();
  53282. for (var i = 0; i < values.length; i++)
  53283. split.push(parseFloat(values[i]));
  53284. if (target instanceof BABYLON.Vector3)
  53285. return BABYLON.Vector3.FromArray(split);
  53286. if (target instanceof BABYLON.Vector4)
  53287. return BABYLON.Vector4.FromArray(split);
  53288. if (target instanceof BABYLON.Color3)
  53289. return BABYLON.Color3.FromArray(split);
  53290. if (target instanceof BABYLON.Color4)
  53291. return BABYLON.Color4.FromArray(split);
  53292. return parseFloat(values[0]);
  53293. };
  53294. // traverse graph per trigger
  53295. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53296. if (combineArray === void 0) { combineArray = null; }
  53297. if (parsedAction.detached)
  53298. return;
  53299. var parameters = new Array();
  53300. var target = null;
  53301. var propertyPath = null;
  53302. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53303. // Parameters
  53304. if (parsedAction.type === 2)
  53305. parameters.push(actionManager);
  53306. else
  53307. parameters.push(trigger);
  53308. if (combine) {
  53309. var actions = new Array();
  53310. for (var j = 0; j < parsedAction.combine.length; j++) {
  53311. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53312. }
  53313. parameters.push(actions);
  53314. }
  53315. else {
  53316. for (var i = 0; i < parsedAction.properties.length; i++) {
  53317. var value = parsedAction.properties[i].value;
  53318. var name = parsedAction.properties[i].name;
  53319. var targetType = parsedAction.properties[i].targetType;
  53320. if (name === "target")
  53321. if (targetType !== null && targetType === "SceneProperties")
  53322. value = target = scene;
  53323. else
  53324. value = target = scene.getNodeByName(value);
  53325. else if (name === "parent")
  53326. value = scene.getNodeByName(value);
  53327. else if (name === "sound")
  53328. value = scene.getSoundByName(value);
  53329. else if (name !== "propertyPath") {
  53330. if (parsedAction.type === 2 && name === "operator")
  53331. value = BABYLON.ValueCondition[value];
  53332. else
  53333. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53334. }
  53335. else {
  53336. propertyPath = value;
  53337. }
  53338. parameters.push(value);
  53339. }
  53340. }
  53341. if (combineArray === null) {
  53342. parameters.push(condition);
  53343. }
  53344. else {
  53345. parameters.push(null);
  53346. }
  53347. // If interpolate value action
  53348. if (parsedAction.name === "InterpolateValueAction") {
  53349. var param = parameters[parameters.length - 2];
  53350. parameters[parameters.length - 1] = param;
  53351. parameters[parameters.length - 2] = condition;
  53352. }
  53353. // Action or condition(s) and not CombineAction
  53354. var newAction = instanciate(parsedAction.name, parameters);
  53355. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53356. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53357. if (action)
  53358. action.then(nothing);
  53359. else
  53360. actionManager.registerAction(nothing);
  53361. action = nothing;
  53362. }
  53363. if (combineArray === null) {
  53364. if (newAction instanceof BABYLON.Condition) {
  53365. condition = newAction;
  53366. newAction = action;
  53367. }
  53368. else {
  53369. condition = null;
  53370. if (action)
  53371. action.then(newAction);
  53372. else
  53373. actionManager.registerAction(newAction);
  53374. }
  53375. }
  53376. else {
  53377. combineArray.push(newAction);
  53378. }
  53379. for (var i = 0; i < parsedAction.children.length; i++)
  53380. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53381. };
  53382. // triggers
  53383. for (var i = 0; i < parsedActions.children.length; i++) {
  53384. var triggerParams;
  53385. var trigger = parsedActions.children[i];
  53386. if (trigger.properties.length > 0) {
  53387. var param = trigger.properties[0].value;
  53388. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53389. if (value._meshId) {
  53390. value.mesh = scene.getMeshByID(value._meshId);
  53391. }
  53392. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53393. }
  53394. else
  53395. triggerParams = ActionManager[trigger.name];
  53396. for (var j = 0; j < trigger.children.length; j++) {
  53397. if (!trigger.detached)
  53398. traverse(trigger.children[j], triggerParams, null, null);
  53399. }
  53400. }
  53401. };
  53402. /**
  53403. * Get a trigger name by index
  53404. * @param trigger defines the trigger index
  53405. * @returns a trigger name
  53406. */
  53407. ActionManager.GetTriggerName = function (trigger) {
  53408. switch (trigger) {
  53409. case 0: return "NothingTrigger";
  53410. case 1: return "OnPickTrigger";
  53411. case 2: return "OnLeftPickTrigger";
  53412. case 3: return "OnRightPickTrigger";
  53413. case 4: return "OnCenterPickTrigger";
  53414. case 5: return "OnPickDownTrigger";
  53415. case 6: return "OnPickUpTrigger";
  53416. case 7: return "OnLongPressTrigger";
  53417. case 8: return "OnPointerOverTrigger";
  53418. case 9: return "OnPointerOutTrigger";
  53419. case 10: return "OnEveryFrameTrigger";
  53420. case 11: return "OnIntersectionEnterTrigger";
  53421. case 12: return "OnIntersectionExitTrigger";
  53422. case 13: return "OnKeyDownTrigger";
  53423. case 14: return "OnKeyUpTrigger";
  53424. case 15: return "OnPickOutTrigger";
  53425. default: return "";
  53426. }
  53427. };
  53428. // Statics
  53429. ActionManager._NothingTrigger = 0;
  53430. ActionManager._OnPickTrigger = 1;
  53431. ActionManager._OnLeftPickTrigger = 2;
  53432. ActionManager._OnRightPickTrigger = 3;
  53433. ActionManager._OnCenterPickTrigger = 4;
  53434. ActionManager._OnPickDownTrigger = 5;
  53435. ActionManager._OnDoublePickTrigger = 6;
  53436. ActionManager._OnPickUpTrigger = 7;
  53437. ActionManager._OnLongPressTrigger = 8;
  53438. ActionManager._OnPointerOverTrigger = 9;
  53439. ActionManager._OnPointerOutTrigger = 10;
  53440. ActionManager._OnEveryFrameTrigger = 11;
  53441. ActionManager._OnIntersectionEnterTrigger = 12;
  53442. ActionManager._OnIntersectionExitTrigger = 13;
  53443. ActionManager._OnKeyDownTrigger = 14;
  53444. ActionManager._OnKeyUpTrigger = 15;
  53445. ActionManager._OnPickOutTrigger = 16;
  53446. /** Gets the list of active triggers */
  53447. ActionManager.Triggers = {};
  53448. return ActionManager;
  53449. }());
  53450. BABYLON.ActionManager = ActionManager;
  53451. })(BABYLON || (BABYLON = {}));
  53452. //# sourceMappingURL=babylon.actionManager.js.map
  53453. var BABYLON;
  53454. (function (BABYLON) {
  53455. var InterpolateValueAction = /** @class */ (function (_super) {
  53456. __extends(InterpolateValueAction, _super);
  53457. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53458. if (duration === void 0) { duration = 1000; }
  53459. var _this = _super.call(this, triggerOptions, condition) || this;
  53460. _this.propertyPath = propertyPath;
  53461. _this.value = value;
  53462. _this.duration = duration;
  53463. _this.stopOtherAnimations = stopOtherAnimations;
  53464. _this.onInterpolationDone = onInterpolationDone;
  53465. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53466. _this._target = _this._effectiveTarget = target;
  53467. return _this;
  53468. }
  53469. /** @hidden */
  53470. InterpolateValueAction.prototype._prepare = function () {
  53471. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53472. this._property = this._getProperty(this.propertyPath);
  53473. };
  53474. InterpolateValueAction.prototype.execute = function () {
  53475. var _this = this;
  53476. var scene = this._actionManager.getScene();
  53477. var keys = [
  53478. {
  53479. frame: 0,
  53480. value: this._effectiveTarget[this._property]
  53481. }, {
  53482. frame: 100,
  53483. value: this.value
  53484. }
  53485. ];
  53486. var dataType;
  53487. if (typeof this.value === "number") {
  53488. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53489. }
  53490. else if (this.value instanceof BABYLON.Color3) {
  53491. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53492. }
  53493. else if (this.value instanceof BABYLON.Vector3) {
  53494. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53495. }
  53496. else if (this.value instanceof BABYLON.Matrix) {
  53497. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53498. }
  53499. else if (this.value instanceof BABYLON.Quaternion) {
  53500. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53501. }
  53502. else {
  53503. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53504. return;
  53505. }
  53506. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53507. animation.setKeys(keys);
  53508. if (this.stopOtherAnimations) {
  53509. scene.stopAnimation(this._effectiveTarget);
  53510. }
  53511. var wrapper = function () {
  53512. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53513. if (_this.onInterpolationDone) {
  53514. _this.onInterpolationDone();
  53515. }
  53516. };
  53517. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53518. };
  53519. InterpolateValueAction.prototype.serialize = function (parent) {
  53520. return _super.prototype._serialize.call(this, {
  53521. name: "InterpolateValueAction",
  53522. properties: [
  53523. BABYLON.Action._GetTargetProperty(this._target),
  53524. { name: "propertyPath", value: this.propertyPath },
  53525. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53526. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53527. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53528. ]
  53529. }, parent);
  53530. };
  53531. return InterpolateValueAction;
  53532. }(BABYLON.Action));
  53533. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53534. })(BABYLON || (BABYLON = {}));
  53535. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53536. var BABYLON;
  53537. (function (BABYLON) {
  53538. var SwitchBooleanAction = /** @class */ (function (_super) {
  53539. __extends(SwitchBooleanAction, _super);
  53540. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53541. var _this = _super.call(this, triggerOptions, condition) || this;
  53542. _this.propertyPath = propertyPath;
  53543. _this._target = _this._effectiveTarget = target;
  53544. return _this;
  53545. }
  53546. /** @hidden */
  53547. SwitchBooleanAction.prototype._prepare = function () {
  53548. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53549. this._property = this._getProperty(this.propertyPath);
  53550. };
  53551. SwitchBooleanAction.prototype.execute = function () {
  53552. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53553. };
  53554. SwitchBooleanAction.prototype.serialize = function (parent) {
  53555. return _super.prototype._serialize.call(this, {
  53556. name: "SwitchBooleanAction",
  53557. properties: [
  53558. BABYLON.Action._GetTargetProperty(this._target),
  53559. { name: "propertyPath", value: this.propertyPath }
  53560. ]
  53561. }, parent);
  53562. };
  53563. return SwitchBooleanAction;
  53564. }(BABYLON.Action));
  53565. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53566. var SetStateAction = /** @class */ (function (_super) {
  53567. __extends(SetStateAction, _super);
  53568. function SetStateAction(triggerOptions, target, value, condition) {
  53569. var _this = _super.call(this, triggerOptions, condition) || this;
  53570. _this.value = value;
  53571. _this._target = target;
  53572. return _this;
  53573. }
  53574. SetStateAction.prototype.execute = function () {
  53575. this._target.state = this.value;
  53576. };
  53577. SetStateAction.prototype.serialize = function (parent) {
  53578. return _super.prototype._serialize.call(this, {
  53579. name: "SetStateAction",
  53580. properties: [
  53581. BABYLON.Action._GetTargetProperty(this._target),
  53582. { name: "value", value: this.value }
  53583. ]
  53584. }, parent);
  53585. };
  53586. return SetStateAction;
  53587. }(BABYLON.Action));
  53588. BABYLON.SetStateAction = SetStateAction;
  53589. var SetValueAction = /** @class */ (function (_super) {
  53590. __extends(SetValueAction, _super);
  53591. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53592. var _this = _super.call(this, triggerOptions, condition) || this;
  53593. _this.propertyPath = propertyPath;
  53594. _this.value = value;
  53595. _this._target = _this._effectiveTarget = target;
  53596. return _this;
  53597. }
  53598. /** @hidden */
  53599. SetValueAction.prototype._prepare = function () {
  53600. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53601. this._property = this._getProperty(this.propertyPath);
  53602. };
  53603. SetValueAction.prototype.execute = function () {
  53604. this._effectiveTarget[this._property] = this.value;
  53605. if (this._target.markAsDirty) {
  53606. this._target.markAsDirty(this._property);
  53607. }
  53608. };
  53609. SetValueAction.prototype.serialize = function (parent) {
  53610. return _super.prototype._serialize.call(this, {
  53611. name: "SetValueAction",
  53612. properties: [
  53613. BABYLON.Action._GetTargetProperty(this._target),
  53614. { name: "propertyPath", value: this.propertyPath },
  53615. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53616. ]
  53617. }, parent);
  53618. };
  53619. return SetValueAction;
  53620. }(BABYLON.Action));
  53621. BABYLON.SetValueAction = SetValueAction;
  53622. var IncrementValueAction = /** @class */ (function (_super) {
  53623. __extends(IncrementValueAction, _super);
  53624. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53625. var _this = _super.call(this, triggerOptions, condition) || this;
  53626. _this.propertyPath = propertyPath;
  53627. _this.value = value;
  53628. _this._target = _this._effectiveTarget = target;
  53629. return _this;
  53630. }
  53631. /** @hidden */
  53632. IncrementValueAction.prototype._prepare = function () {
  53633. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53634. this._property = this._getProperty(this.propertyPath);
  53635. if (typeof this._effectiveTarget[this._property] !== "number") {
  53636. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53637. }
  53638. };
  53639. IncrementValueAction.prototype.execute = function () {
  53640. this._effectiveTarget[this._property] += this.value;
  53641. if (this._target.markAsDirty) {
  53642. this._target.markAsDirty(this._property);
  53643. }
  53644. };
  53645. IncrementValueAction.prototype.serialize = function (parent) {
  53646. return _super.prototype._serialize.call(this, {
  53647. name: "IncrementValueAction",
  53648. properties: [
  53649. BABYLON.Action._GetTargetProperty(this._target),
  53650. { name: "propertyPath", value: this.propertyPath },
  53651. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53652. ]
  53653. }, parent);
  53654. };
  53655. return IncrementValueAction;
  53656. }(BABYLON.Action));
  53657. BABYLON.IncrementValueAction = IncrementValueAction;
  53658. var PlayAnimationAction = /** @class */ (function (_super) {
  53659. __extends(PlayAnimationAction, _super);
  53660. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53661. var _this = _super.call(this, triggerOptions, condition) || this;
  53662. _this.from = from;
  53663. _this.to = to;
  53664. _this.loop = loop;
  53665. _this._target = target;
  53666. return _this;
  53667. }
  53668. /** @hidden */
  53669. PlayAnimationAction.prototype._prepare = function () {
  53670. };
  53671. PlayAnimationAction.prototype.execute = function () {
  53672. var scene = this._actionManager.getScene();
  53673. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53674. };
  53675. PlayAnimationAction.prototype.serialize = function (parent) {
  53676. return _super.prototype._serialize.call(this, {
  53677. name: "PlayAnimationAction",
  53678. properties: [
  53679. BABYLON.Action._GetTargetProperty(this._target),
  53680. { name: "from", value: String(this.from) },
  53681. { name: "to", value: String(this.to) },
  53682. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53683. ]
  53684. }, parent);
  53685. };
  53686. return PlayAnimationAction;
  53687. }(BABYLON.Action));
  53688. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53689. var StopAnimationAction = /** @class */ (function (_super) {
  53690. __extends(StopAnimationAction, _super);
  53691. function StopAnimationAction(triggerOptions, target, condition) {
  53692. var _this = _super.call(this, triggerOptions, condition) || this;
  53693. _this._target = target;
  53694. return _this;
  53695. }
  53696. /** @hidden */
  53697. StopAnimationAction.prototype._prepare = function () {
  53698. };
  53699. StopAnimationAction.prototype.execute = function () {
  53700. var scene = this._actionManager.getScene();
  53701. scene.stopAnimation(this._target);
  53702. };
  53703. StopAnimationAction.prototype.serialize = function (parent) {
  53704. return _super.prototype._serialize.call(this, {
  53705. name: "StopAnimationAction",
  53706. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53707. }, parent);
  53708. };
  53709. return StopAnimationAction;
  53710. }(BABYLON.Action));
  53711. BABYLON.StopAnimationAction = StopAnimationAction;
  53712. var DoNothingAction = /** @class */ (function (_super) {
  53713. __extends(DoNothingAction, _super);
  53714. function DoNothingAction(triggerOptions, condition) {
  53715. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53716. return _super.call(this, triggerOptions, condition) || this;
  53717. }
  53718. DoNothingAction.prototype.execute = function () {
  53719. };
  53720. DoNothingAction.prototype.serialize = function (parent) {
  53721. return _super.prototype._serialize.call(this, {
  53722. name: "DoNothingAction",
  53723. properties: []
  53724. }, parent);
  53725. };
  53726. return DoNothingAction;
  53727. }(BABYLON.Action));
  53728. BABYLON.DoNothingAction = DoNothingAction;
  53729. var CombineAction = /** @class */ (function (_super) {
  53730. __extends(CombineAction, _super);
  53731. function CombineAction(triggerOptions, children, condition) {
  53732. var _this = _super.call(this, triggerOptions, condition) || this;
  53733. _this.children = children;
  53734. return _this;
  53735. }
  53736. /** @hidden */
  53737. CombineAction.prototype._prepare = function () {
  53738. for (var index = 0; index < this.children.length; index++) {
  53739. this.children[index]._actionManager = this._actionManager;
  53740. this.children[index]._prepare();
  53741. }
  53742. };
  53743. CombineAction.prototype.execute = function (evt) {
  53744. for (var index = 0; index < this.children.length; index++) {
  53745. this.children[index].execute(evt);
  53746. }
  53747. };
  53748. CombineAction.prototype.serialize = function (parent) {
  53749. var serializationObject = _super.prototype._serialize.call(this, {
  53750. name: "CombineAction",
  53751. properties: [],
  53752. combine: []
  53753. }, parent);
  53754. for (var i = 0; i < this.children.length; i++) {
  53755. serializationObject.combine.push(this.children[i].serialize(null));
  53756. }
  53757. return serializationObject;
  53758. };
  53759. return CombineAction;
  53760. }(BABYLON.Action));
  53761. BABYLON.CombineAction = CombineAction;
  53762. var ExecuteCodeAction = /** @class */ (function (_super) {
  53763. __extends(ExecuteCodeAction, _super);
  53764. function ExecuteCodeAction(triggerOptions, func, condition) {
  53765. var _this = _super.call(this, triggerOptions, condition) || this;
  53766. _this.func = func;
  53767. return _this;
  53768. }
  53769. ExecuteCodeAction.prototype.execute = function (evt) {
  53770. this.func(evt);
  53771. };
  53772. return ExecuteCodeAction;
  53773. }(BABYLON.Action));
  53774. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53775. var SetParentAction = /** @class */ (function (_super) {
  53776. __extends(SetParentAction, _super);
  53777. function SetParentAction(triggerOptions, target, parent, condition) {
  53778. var _this = _super.call(this, triggerOptions, condition) || this;
  53779. _this._target = target;
  53780. _this._parent = parent;
  53781. return _this;
  53782. }
  53783. /** @hidden */
  53784. SetParentAction.prototype._prepare = function () {
  53785. };
  53786. SetParentAction.prototype.execute = function () {
  53787. if (this._target.parent === this._parent) {
  53788. return;
  53789. }
  53790. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53791. invertParentWorldMatrix.invert();
  53792. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53793. this._target.parent = this._parent;
  53794. };
  53795. SetParentAction.prototype.serialize = function (parent) {
  53796. return _super.prototype._serialize.call(this, {
  53797. name: "SetParentAction",
  53798. properties: [
  53799. BABYLON.Action._GetTargetProperty(this._target),
  53800. BABYLON.Action._GetTargetProperty(this._parent),
  53801. ]
  53802. }, parent);
  53803. };
  53804. return SetParentAction;
  53805. }(BABYLON.Action));
  53806. BABYLON.SetParentAction = SetParentAction;
  53807. var PlaySoundAction = /** @class */ (function (_super) {
  53808. __extends(PlaySoundAction, _super);
  53809. function PlaySoundAction(triggerOptions, sound, condition) {
  53810. var _this = _super.call(this, triggerOptions, condition) || this;
  53811. _this._sound = sound;
  53812. return _this;
  53813. }
  53814. /** @hidden */
  53815. PlaySoundAction.prototype._prepare = function () {
  53816. };
  53817. PlaySoundAction.prototype.execute = function () {
  53818. if (this._sound !== undefined)
  53819. this._sound.play();
  53820. };
  53821. PlaySoundAction.prototype.serialize = function (parent) {
  53822. return _super.prototype._serialize.call(this, {
  53823. name: "PlaySoundAction",
  53824. properties: [{ name: "sound", value: this._sound.name }]
  53825. }, parent);
  53826. };
  53827. return PlaySoundAction;
  53828. }(BABYLON.Action));
  53829. BABYLON.PlaySoundAction = PlaySoundAction;
  53830. var StopSoundAction = /** @class */ (function (_super) {
  53831. __extends(StopSoundAction, _super);
  53832. function StopSoundAction(triggerOptions, sound, condition) {
  53833. var _this = _super.call(this, triggerOptions, condition) || this;
  53834. _this._sound = sound;
  53835. return _this;
  53836. }
  53837. /** @hidden */
  53838. StopSoundAction.prototype._prepare = function () {
  53839. };
  53840. StopSoundAction.prototype.execute = function () {
  53841. if (this._sound !== undefined)
  53842. this._sound.stop();
  53843. };
  53844. StopSoundAction.prototype.serialize = function (parent) {
  53845. return _super.prototype._serialize.call(this, {
  53846. name: "StopSoundAction",
  53847. properties: [{ name: "sound", value: this._sound.name }]
  53848. }, parent);
  53849. };
  53850. return StopSoundAction;
  53851. }(BABYLON.Action));
  53852. BABYLON.StopSoundAction = StopSoundAction;
  53853. })(BABYLON || (BABYLON = {}));
  53854. //# sourceMappingURL=babylon.directActions.js.map
  53855. var BABYLON;
  53856. (function (BABYLON) {
  53857. var SpriteManager = /** @class */ (function () {
  53858. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53859. if (epsilon === void 0) { epsilon = 0.01; }
  53860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53861. this.name = name;
  53862. this.sprites = new Array();
  53863. this.renderingGroupId = 0;
  53864. this.layerMask = 0x0FFFFFFF;
  53865. this.fogEnabled = true;
  53866. this.isPickable = false;
  53867. /**
  53868. * An event triggered when the manager is disposed.
  53869. */
  53870. this.onDisposeObservable = new BABYLON.Observable();
  53871. this._vertexBuffers = {};
  53872. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53873. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53874. }
  53875. this._capacity = capacity;
  53876. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53877. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53878. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53879. if (cellSize.width && cellSize.height) {
  53880. this.cellWidth = cellSize.width;
  53881. this.cellHeight = cellSize.height;
  53882. }
  53883. else if (cellSize !== undefined) {
  53884. this.cellWidth = cellSize;
  53885. this.cellHeight = cellSize;
  53886. }
  53887. else {
  53888. return;
  53889. }
  53890. this._epsilon = epsilon;
  53891. this._scene = scene;
  53892. this._scene.spriteManagers.push(this);
  53893. var indices = [];
  53894. var index = 0;
  53895. for (var count = 0; count < capacity; count++) {
  53896. indices.push(index);
  53897. indices.push(index + 1);
  53898. indices.push(index + 2);
  53899. indices.push(index);
  53900. indices.push(index + 2);
  53901. indices.push(index + 3);
  53902. index += 4;
  53903. }
  53904. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53905. // VBO
  53906. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53907. this._vertexData = new Float32Array(capacity * 16 * 4);
  53908. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53909. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53910. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53911. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53912. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53913. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53914. this._vertexBuffers["options"] = options;
  53915. this._vertexBuffers["cellInfo"] = cellInfo;
  53916. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53917. // Effects
  53918. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53919. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53920. }
  53921. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53922. set: function (callback) {
  53923. if (this._onDisposeObserver) {
  53924. this.onDisposeObservable.remove(this._onDisposeObserver);
  53925. }
  53926. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53927. },
  53928. enumerable: true,
  53929. configurable: true
  53930. });
  53931. Object.defineProperty(SpriteManager.prototype, "texture", {
  53932. get: function () {
  53933. return this._spriteTexture;
  53934. },
  53935. set: function (value) {
  53936. this._spriteTexture = value;
  53937. },
  53938. enumerable: true,
  53939. configurable: true
  53940. });
  53941. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53942. var arrayOffset = index * 16;
  53943. if (offsetX === 0)
  53944. offsetX = this._epsilon;
  53945. else if (offsetX === 1)
  53946. offsetX = 1 - this._epsilon;
  53947. if (offsetY === 0)
  53948. offsetY = this._epsilon;
  53949. else if (offsetY === 1)
  53950. offsetY = 1 - this._epsilon;
  53951. this._vertexData[arrayOffset] = sprite.position.x;
  53952. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53953. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53954. this._vertexData[arrayOffset + 3] = sprite.angle;
  53955. this._vertexData[arrayOffset + 4] = sprite.width;
  53956. this._vertexData[arrayOffset + 5] = sprite.height;
  53957. this._vertexData[arrayOffset + 6] = offsetX;
  53958. this._vertexData[arrayOffset + 7] = offsetY;
  53959. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53960. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53961. var offset = (sprite.cellIndex / rowSize) >> 0;
  53962. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53963. this._vertexData[arrayOffset + 11] = offset;
  53964. // Color
  53965. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53966. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53967. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53968. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53969. };
  53970. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53971. var count = Math.min(this._capacity, this.sprites.length);
  53972. var min = BABYLON.Vector3.Zero();
  53973. var max = BABYLON.Vector3.Zero();
  53974. var distance = Number.MAX_VALUE;
  53975. var currentSprite = null;
  53976. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53977. var cameraView = camera.getViewMatrix();
  53978. for (var index = 0; index < count; index++) {
  53979. var sprite = this.sprites[index];
  53980. if (!sprite) {
  53981. continue;
  53982. }
  53983. if (predicate) {
  53984. if (!predicate(sprite)) {
  53985. continue;
  53986. }
  53987. }
  53988. else if (!sprite.isPickable) {
  53989. continue;
  53990. }
  53991. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53992. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53993. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53994. if (ray.intersectsBoxMinMax(min, max)) {
  53995. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53996. if (distance > currentDistance) {
  53997. distance = currentDistance;
  53998. currentSprite = sprite;
  53999. if (fastCheck) {
  54000. break;
  54001. }
  54002. }
  54003. }
  54004. }
  54005. if (currentSprite) {
  54006. var result = new BABYLON.PickingInfo();
  54007. result.hit = true;
  54008. result.pickedSprite = currentSprite;
  54009. result.distance = distance;
  54010. return result;
  54011. }
  54012. return null;
  54013. };
  54014. SpriteManager.prototype.render = function () {
  54015. // Check
  54016. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54017. return;
  54018. var engine = this._scene.getEngine();
  54019. var baseSize = this._spriteTexture.getBaseSize();
  54020. // Sprites
  54021. var deltaTime = engine.getDeltaTime();
  54022. var max = Math.min(this._capacity, this.sprites.length);
  54023. var rowSize = baseSize.width / this.cellWidth;
  54024. var offset = 0;
  54025. for (var index = 0; index < max; index++) {
  54026. var sprite = this.sprites[index];
  54027. if (!sprite || !sprite.isVisible) {
  54028. continue;
  54029. }
  54030. sprite._animate(deltaTime);
  54031. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54032. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54033. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54034. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54035. }
  54036. this._buffer.update(this._vertexData);
  54037. // Render
  54038. var effect = this._effectBase;
  54039. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54040. effect = this._effectFog;
  54041. }
  54042. engine.enableEffect(effect);
  54043. var viewMatrix = this._scene.getViewMatrix();
  54044. effect.setTexture("diffuseSampler", this._spriteTexture);
  54045. effect.setMatrix("view", viewMatrix);
  54046. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54047. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54048. // Fog
  54049. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54050. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54051. effect.setColor3("vFogColor", this._scene.fogColor);
  54052. }
  54053. // VBOs
  54054. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54055. // Draw order
  54056. engine.setDepthFunctionToLessOrEqual();
  54057. effect.setBool("alphaTest", true);
  54058. engine.setColorWrite(false);
  54059. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54060. engine.setColorWrite(true);
  54061. effect.setBool("alphaTest", false);
  54062. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54063. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54064. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54065. };
  54066. SpriteManager.prototype.dispose = function () {
  54067. if (this._buffer) {
  54068. this._buffer.dispose();
  54069. this._buffer = null;
  54070. }
  54071. if (this._indexBuffer) {
  54072. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54073. this._indexBuffer = null;
  54074. }
  54075. if (this._spriteTexture) {
  54076. this._spriteTexture.dispose();
  54077. this._spriteTexture = null;
  54078. }
  54079. // Remove from scene
  54080. var index = this._scene.spriteManagers.indexOf(this);
  54081. this._scene.spriteManagers.splice(index, 1);
  54082. // Callback
  54083. this.onDisposeObservable.notifyObservers(this);
  54084. this.onDisposeObservable.clear();
  54085. };
  54086. return SpriteManager;
  54087. }());
  54088. BABYLON.SpriteManager = SpriteManager;
  54089. })(BABYLON || (BABYLON = {}));
  54090. //# sourceMappingURL=babylon.spriteManager.js.map
  54091. var BABYLON;
  54092. (function (BABYLON) {
  54093. var Sprite = /** @class */ (function () {
  54094. function Sprite(name, manager) {
  54095. this.name = name;
  54096. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54097. this.width = 1.0;
  54098. this.height = 1.0;
  54099. this.angle = 0;
  54100. this.cellIndex = 0;
  54101. this.invertU = 0;
  54102. this.invertV = 0;
  54103. this.animations = new Array();
  54104. this.isPickable = false;
  54105. this._animationStarted = false;
  54106. this._loopAnimation = false;
  54107. this._fromIndex = 0;
  54108. this._toIndex = 0;
  54109. this._delay = 0;
  54110. this._direction = 1;
  54111. this._time = 0;
  54112. /**
  54113. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54114. */
  54115. this.isVisible = true;
  54116. this._manager = manager;
  54117. this._manager.sprites.push(this);
  54118. this.position = BABYLON.Vector3.Zero();
  54119. }
  54120. Object.defineProperty(Sprite.prototype, "size", {
  54121. get: function () {
  54122. return this.width;
  54123. },
  54124. set: function (value) {
  54125. this.width = value;
  54126. this.height = value;
  54127. },
  54128. enumerable: true,
  54129. configurable: true
  54130. });
  54131. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54132. this._fromIndex = from;
  54133. this._toIndex = to;
  54134. this._loopAnimation = loop;
  54135. this._delay = delay;
  54136. this._animationStarted = true;
  54137. this._direction = from < to ? 1 : -1;
  54138. this.cellIndex = from;
  54139. this._time = 0;
  54140. this._onAnimationEnd = onAnimationEnd;
  54141. };
  54142. Sprite.prototype.stopAnimation = function () {
  54143. this._animationStarted = false;
  54144. };
  54145. /** @hidden */
  54146. Sprite.prototype._animate = function (deltaTime) {
  54147. if (!this._animationStarted)
  54148. return;
  54149. this._time += deltaTime;
  54150. if (this._time > this._delay) {
  54151. this._time = this._time % this._delay;
  54152. this.cellIndex += this._direction;
  54153. if (this.cellIndex > this._toIndex) {
  54154. if (this._loopAnimation) {
  54155. this.cellIndex = this._fromIndex;
  54156. }
  54157. else {
  54158. this.cellIndex = this._toIndex;
  54159. this._animationStarted = false;
  54160. if (this._onAnimationEnd) {
  54161. this._onAnimationEnd();
  54162. }
  54163. if (this.disposeWhenFinishedAnimating) {
  54164. this.dispose();
  54165. }
  54166. }
  54167. }
  54168. }
  54169. };
  54170. Sprite.prototype.dispose = function () {
  54171. for (var i = 0; i < this._manager.sprites.length; i++) {
  54172. if (this._manager.sprites[i] == this) {
  54173. this._manager.sprites.splice(i, 1);
  54174. }
  54175. }
  54176. };
  54177. return Sprite;
  54178. }());
  54179. BABYLON.Sprite = Sprite;
  54180. })(BABYLON || (BABYLON = {}));
  54181. //# sourceMappingURL=babylon.sprite.js.map
  54182. var BABYLON;
  54183. (function (BABYLON) {
  54184. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54185. if (!BABYLON.PickingInfo) {
  54186. return null;
  54187. }
  54188. var pickingInfo = null;
  54189. if (!camera) {
  54190. if (!this.activeCamera) {
  54191. return null;
  54192. }
  54193. camera = this.activeCamera;
  54194. }
  54195. if (this.spriteManagers.length > 0) {
  54196. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54197. var spriteManager = this.spriteManagers[spriteIndex];
  54198. if (!spriteManager.isPickable) {
  54199. continue;
  54200. }
  54201. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54202. if (!result || !result.hit)
  54203. continue;
  54204. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54205. continue;
  54206. pickingInfo = result;
  54207. if (fastCheck) {
  54208. break;
  54209. }
  54210. }
  54211. }
  54212. return pickingInfo || new BABYLON.PickingInfo();
  54213. };
  54214. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54215. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54216. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54217. };
  54218. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54219. if (!this._tempSpritePickingRay) {
  54220. return null;
  54221. }
  54222. if (!camera) {
  54223. if (!this.activeCamera) {
  54224. return null;
  54225. }
  54226. camera = this.activeCamera;
  54227. }
  54228. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54229. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54230. };
  54231. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54232. if (this._pointerOverSprite === sprite) {
  54233. return;
  54234. }
  54235. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54236. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54237. }
  54238. this._pointerOverSprite = sprite;
  54239. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54240. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54241. }
  54242. };
  54243. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54244. return this._pointerOverSprite;
  54245. };
  54246. /**
  54247. * Defines the sprite scene component responsible to manage sprites
  54248. * in a given scene.
  54249. */
  54250. var SpriteSceneComponent = /** @class */ (function () {
  54251. /**
  54252. * Creates a new instance of the component for the given scene
  54253. * @param scene Defines the scene to register the component in
  54254. */
  54255. function SpriteSceneComponent(scene) {
  54256. /**
  54257. * The component name helpfull to identify the component in the list of scene components.
  54258. */
  54259. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54260. this.scene = scene;
  54261. this.scene.spriteManagers = new Array();
  54262. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54263. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54264. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54265. this._spritePredicate = function (sprite) {
  54266. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54267. };
  54268. }
  54269. /**
  54270. * Registers the component in a given scene
  54271. */
  54272. SpriteSceneComponent.prototype.register = function () {
  54273. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54274. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54275. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54276. };
  54277. /**
  54278. * Rebuilds the elements related to this component in case of
  54279. * context lost for instance.
  54280. */
  54281. SpriteSceneComponent.prototype.rebuild = function () {
  54282. /** Nothing to do for sprites */
  54283. };
  54284. /**
  54285. * Disposes the component and the associated ressources.
  54286. */
  54287. SpriteSceneComponent.prototype.dispose = function () {
  54288. this.scene.onBeforeSpritesRenderingObservable.clear();
  54289. this.scene.onAfterSpritesRenderingObservable.clear();
  54290. var spriteManagers = this.scene.spriteManagers;
  54291. while (spriteManagers.length) {
  54292. spriteManagers[0].dispose();
  54293. }
  54294. };
  54295. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54296. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54297. if (result) {
  54298. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54299. }
  54300. return result;
  54301. };
  54302. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54303. var scene = this.scene;
  54304. if (isMeshPicked) {
  54305. scene.setPointerOverSprite(null);
  54306. }
  54307. else {
  54308. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54309. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54310. scene.setPointerOverSprite(pickResult.pickedSprite);
  54311. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54312. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54313. }
  54314. else {
  54315. canvas.style.cursor = scene.hoverCursor;
  54316. }
  54317. }
  54318. else {
  54319. scene.setPointerOverSprite(null);
  54320. // Restore pointer
  54321. canvas.style.cursor = scene.defaultCursor;
  54322. }
  54323. }
  54324. return pickResult;
  54325. };
  54326. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54327. var scene = this.scene;
  54328. scene._pickedDownSprite = null;
  54329. if (scene.spriteManagers.length > 0) {
  54330. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54331. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54332. if (pickResult.pickedSprite.actionManager) {
  54333. scene._pickedDownSprite = pickResult.pickedSprite;
  54334. switch (evt.button) {
  54335. case 0:
  54336. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54337. break;
  54338. case 1:
  54339. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54340. break;
  54341. case 2:
  54342. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54343. break;
  54344. }
  54345. if (pickResult.pickedSprite.actionManager) {
  54346. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54347. }
  54348. }
  54349. }
  54350. }
  54351. return pickResult;
  54352. };
  54353. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54354. var scene = this.scene;
  54355. if (scene.spriteManagers.length > 0) {
  54356. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54357. if (spritePickResult) {
  54358. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54359. if (spritePickResult.pickedSprite.actionManager) {
  54360. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54361. if (spritePickResult.pickedSprite.actionManager) {
  54362. if (!this.scene._isPointerSwiping()) {
  54363. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54364. }
  54365. }
  54366. }
  54367. }
  54368. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54369. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54370. }
  54371. }
  54372. }
  54373. return pickResult;
  54374. };
  54375. return SpriteSceneComponent;
  54376. }());
  54377. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54378. })(BABYLON || (BABYLON = {}));
  54379. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54380. var BABYLON;
  54381. (function (BABYLON) {
  54382. var IntersectionInfo = /** @class */ (function () {
  54383. function IntersectionInfo(bu, bv, distance) {
  54384. this.bu = bu;
  54385. this.bv = bv;
  54386. this.distance = distance;
  54387. this.faceId = 0;
  54388. this.subMeshId = 0;
  54389. }
  54390. return IntersectionInfo;
  54391. }());
  54392. BABYLON.IntersectionInfo = IntersectionInfo;
  54393. /**
  54394. * Information about the result of picking within a scene
  54395. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54396. */
  54397. var PickingInfo = /** @class */ (function () {
  54398. function PickingInfo() {
  54399. /**
  54400. * If the pick collided with an object
  54401. */
  54402. this.hit = false;
  54403. /**
  54404. * Distance away where the pick collided
  54405. */
  54406. this.distance = 0;
  54407. /**
  54408. * The location of pick collision
  54409. */
  54410. this.pickedPoint = null;
  54411. /**
  54412. * The mesh corresponding the the pick collision
  54413. */
  54414. this.pickedMesh = null;
  54415. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54416. this.bu = 0;
  54417. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54418. this.bv = 0;
  54419. /** The id of the face on the mesh that was picked */
  54420. this.faceId = -1;
  54421. /** Id of the the submesh that was picked */
  54422. this.subMeshId = 0;
  54423. /** If a sprite was picked, this will be the sprite the pick collided with */
  54424. this.pickedSprite = null;
  54425. /**
  54426. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54427. */
  54428. this.originMesh = null;
  54429. /**
  54430. * The ray that was used to perform the picking.
  54431. */
  54432. this.ray = null;
  54433. }
  54434. /**
  54435. * Gets the normal correspodning to the face the pick collided with
  54436. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54437. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54438. * @returns The normal correspodning to the face the pick collided with
  54439. */
  54440. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54441. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54442. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54443. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54444. return null;
  54445. }
  54446. var indices = this.pickedMesh.getIndices();
  54447. if (!indices) {
  54448. return null;
  54449. }
  54450. var result;
  54451. if (useVerticesNormals) {
  54452. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54453. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54454. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54455. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54456. normal0 = normal0.scale(this.bu);
  54457. normal1 = normal1.scale(this.bv);
  54458. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54459. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54460. }
  54461. else {
  54462. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54463. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54464. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54465. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54466. var p1p2 = vertex1.subtract(vertex2);
  54467. var p3p2 = vertex3.subtract(vertex2);
  54468. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54469. }
  54470. if (useWorldCoordinates) {
  54471. var wm = this.pickedMesh.getWorldMatrix();
  54472. if (this.pickedMesh.nonUniformScaling) {
  54473. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54474. wm = BABYLON.Tmp.Matrix[0];
  54475. wm.setTranslationFromFloats(0, 0, 0);
  54476. wm.invert();
  54477. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54478. wm = BABYLON.Tmp.Matrix[1];
  54479. }
  54480. result = BABYLON.Vector3.TransformNormal(result, wm);
  54481. }
  54482. result.normalize();
  54483. return result;
  54484. };
  54485. /**
  54486. * Gets the texture coordinates of where the pick occured
  54487. * @returns the vector containing the coordnates of the texture
  54488. */
  54489. PickingInfo.prototype.getTextureCoordinates = function () {
  54490. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54491. return null;
  54492. }
  54493. var indices = this.pickedMesh.getIndices();
  54494. if (!indices) {
  54495. return null;
  54496. }
  54497. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54498. if (!uvs) {
  54499. return null;
  54500. }
  54501. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54502. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54503. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54504. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54505. uv1 = uv1.scale(this.bu);
  54506. uv2 = uv2.scale(this.bv);
  54507. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54508. };
  54509. return PickingInfo;
  54510. }());
  54511. BABYLON.PickingInfo = PickingInfo;
  54512. })(BABYLON || (BABYLON = {}));
  54513. //# sourceMappingURL=babylon.pickingInfo.js.map
  54514. var BABYLON;
  54515. (function (BABYLON) {
  54516. var Ray = /** @class */ (function () {
  54517. function Ray(origin, direction, length) {
  54518. if (length === void 0) { length = Number.MAX_VALUE; }
  54519. this.origin = origin;
  54520. this.direction = direction;
  54521. this.length = length;
  54522. }
  54523. // Methods
  54524. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54525. var d = 0.0;
  54526. var maxValue = Number.MAX_VALUE;
  54527. var inv;
  54528. var min;
  54529. var max;
  54530. var temp;
  54531. if (Math.abs(this.direction.x) < 0.0000001) {
  54532. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54533. return false;
  54534. }
  54535. }
  54536. else {
  54537. inv = 1.0 / this.direction.x;
  54538. min = (minimum.x - this.origin.x) * inv;
  54539. max = (maximum.x - this.origin.x) * inv;
  54540. if (max === -Infinity) {
  54541. max = Infinity;
  54542. }
  54543. if (min > max) {
  54544. temp = min;
  54545. min = max;
  54546. max = temp;
  54547. }
  54548. d = Math.max(min, d);
  54549. maxValue = Math.min(max, maxValue);
  54550. if (d > maxValue) {
  54551. return false;
  54552. }
  54553. }
  54554. if (Math.abs(this.direction.y) < 0.0000001) {
  54555. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54556. return false;
  54557. }
  54558. }
  54559. else {
  54560. inv = 1.0 / this.direction.y;
  54561. min = (minimum.y - this.origin.y) * inv;
  54562. max = (maximum.y - this.origin.y) * inv;
  54563. if (max === -Infinity) {
  54564. max = Infinity;
  54565. }
  54566. if (min > max) {
  54567. temp = min;
  54568. min = max;
  54569. max = temp;
  54570. }
  54571. d = Math.max(min, d);
  54572. maxValue = Math.min(max, maxValue);
  54573. if (d > maxValue) {
  54574. return false;
  54575. }
  54576. }
  54577. if (Math.abs(this.direction.z) < 0.0000001) {
  54578. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54579. return false;
  54580. }
  54581. }
  54582. else {
  54583. inv = 1.0 / this.direction.z;
  54584. min = (minimum.z - this.origin.z) * inv;
  54585. max = (maximum.z - this.origin.z) * inv;
  54586. if (max === -Infinity) {
  54587. max = Infinity;
  54588. }
  54589. if (min > max) {
  54590. temp = min;
  54591. min = max;
  54592. max = temp;
  54593. }
  54594. d = Math.max(min, d);
  54595. maxValue = Math.min(max, maxValue);
  54596. if (d > maxValue) {
  54597. return false;
  54598. }
  54599. }
  54600. return true;
  54601. };
  54602. Ray.prototype.intersectsBox = function (box) {
  54603. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54604. };
  54605. Ray.prototype.intersectsSphere = function (sphere) {
  54606. var x = sphere.center.x - this.origin.x;
  54607. var y = sphere.center.y - this.origin.y;
  54608. var z = sphere.center.z - this.origin.z;
  54609. var pyth = (x * x) + (y * y) + (z * z);
  54610. var rr = sphere.radius * sphere.radius;
  54611. if (pyth <= rr) {
  54612. return true;
  54613. }
  54614. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54615. if (dot < 0.0) {
  54616. return false;
  54617. }
  54618. var temp = pyth - (dot * dot);
  54619. return temp <= rr;
  54620. };
  54621. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54622. if (!this._edge1) {
  54623. this._edge1 = BABYLON.Vector3.Zero();
  54624. this._edge2 = BABYLON.Vector3.Zero();
  54625. this._pvec = BABYLON.Vector3.Zero();
  54626. this._tvec = BABYLON.Vector3.Zero();
  54627. this._qvec = BABYLON.Vector3.Zero();
  54628. }
  54629. vertex1.subtractToRef(vertex0, this._edge1);
  54630. vertex2.subtractToRef(vertex0, this._edge2);
  54631. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54632. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54633. if (det === 0) {
  54634. return null;
  54635. }
  54636. var invdet = 1 / det;
  54637. this.origin.subtractToRef(vertex0, this._tvec);
  54638. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54639. if (bu < 0 || bu > 1.0) {
  54640. return null;
  54641. }
  54642. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54643. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54644. if (bv < 0 || bu + bv > 1.0) {
  54645. return null;
  54646. }
  54647. //check if the distance is longer than the predefined length.
  54648. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54649. if (distance > this.length) {
  54650. return null;
  54651. }
  54652. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54653. };
  54654. Ray.prototype.intersectsPlane = function (plane) {
  54655. var distance;
  54656. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54657. if (Math.abs(result1) < 9.99999997475243E-07) {
  54658. return null;
  54659. }
  54660. else {
  54661. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54662. distance = (-plane.d - result2) / result1;
  54663. if (distance < 0.0) {
  54664. if (distance < -9.99999997475243E-07) {
  54665. return null;
  54666. }
  54667. else {
  54668. return 0;
  54669. }
  54670. }
  54671. return distance;
  54672. }
  54673. };
  54674. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54675. var tm = BABYLON.Tmp.Matrix[0];
  54676. mesh.getWorldMatrix().invertToRef(tm);
  54677. if (this._tmpRay) {
  54678. Ray.TransformToRef(this, tm, this._tmpRay);
  54679. }
  54680. else {
  54681. this._tmpRay = Ray.Transform(this, tm);
  54682. }
  54683. return mesh.intersects(this._tmpRay, fastCheck);
  54684. };
  54685. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54686. if (results) {
  54687. results.length = 0;
  54688. }
  54689. else {
  54690. results = [];
  54691. }
  54692. for (var i = 0; i < meshes.length; i++) {
  54693. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54694. if (pickInfo.hit) {
  54695. results.push(pickInfo);
  54696. }
  54697. }
  54698. results.sort(this._comparePickingInfo);
  54699. return results;
  54700. };
  54701. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54702. if (pickingInfoA.distance < pickingInfoB.distance) {
  54703. return -1;
  54704. }
  54705. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54706. return 1;
  54707. }
  54708. else {
  54709. return 0;
  54710. }
  54711. };
  54712. /**
  54713. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54714. * @param sega the first point of the segment to test the intersection against
  54715. * @param segb the second point of the segment to test the intersection against
  54716. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54717. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54718. */
  54719. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54720. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54721. var u = segb.subtract(sega);
  54722. var v = rsegb.subtract(this.origin);
  54723. var w = sega.subtract(this.origin);
  54724. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54725. var b = BABYLON.Vector3.Dot(u, v);
  54726. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54727. var d = BABYLON.Vector3.Dot(u, w);
  54728. var e = BABYLON.Vector3.Dot(v, w);
  54729. var D = a * c - b * b; // always >= 0
  54730. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54731. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54732. // compute the line parameters of the two closest points
  54733. if (D < Ray.smallnum) { // the lines are almost parallel
  54734. sN = 0.0; // force using point P0 on segment S1
  54735. sD = 1.0; // to prevent possible division by 0.0 later
  54736. tN = e;
  54737. tD = c;
  54738. }
  54739. else { // get the closest points on the infinite lines
  54740. sN = (b * e - c * d);
  54741. tN = (a * e - b * d);
  54742. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54743. sN = 0.0;
  54744. tN = e;
  54745. tD = c;
  54746. }
  54747. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54748. sN = sD;
  54749. tN = e + b;
  54750. tD = c;
  54751. }
  54752. }
  54753. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54754. tN = 0.0;
  54755. // recompute sc for this edge
  54756. if (-d < 0.0) {
  54757. sN = 0.0;
  54758. }
  54759. else if (-d > a)
  54760. sN = sD;
  54761. else {
  54762. sN = -d;
  54763. sD = a;
  54764. }
  54765. }
  54766. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54767. tN = tD;
  54768. // recompute sc for this edge
  54769. if ((-d + b) < 0.0) {
  54770. sN = 0;
  54771. }
  54772. else if ((-d + b) > a) {
  54773. sN = sD;
  54774. }
  54775. else {
  54776. sN = (-d + b);
  54777. sD = a;
  54778. }
  54779. }
  54780. // finally do the division to get sc and tc
  54781. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54782. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54783. // get the difference of the two closest points
  54784. var qtc = v.multiplyByFloats(tc, tc, tc);
  54785. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54786. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54787. if (isIntersected) {
  54788. return qtc.length();
  54789. }
  54790. return -1;
  54791. };
  54792. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54793. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54794. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54795. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54796. this.direction.normalize();
  54797. return this;
  54798. };
  54799. // Statics
  54800. Ray.Zero = function () {
  54801. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54802. };
  54803. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54804. var result = Ray.Zero();
  54805. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54806. };
  54807. /**
  54808. * 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
  54809. * transformed to the given world matrix.
  54810. * @param origin The origin point
  54811. * @param end The end point
  54812. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54813. */
  54814. Ray.CreateNewFromTo = function (origin, end, world) {
  54815. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54816. var direction = end.subtract(origin);
  54817. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54818. direction.normalize();
  54819. return Ray.Transform(new Ray(origin, direction, length), world);
  54820. };
  54821. Ray.Transform = function (ray, matrix) {
  54822. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54823. Ray.TransformToRef(ray, matrix, result);
  54824. return result;
  54825. };
  54826. Ray.TransformToRef = function (ray, matrix, result) {
  54827. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54828. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54829. result.length = ray.length;
  54830. var dir = result.direction;
  54831. var len = dir.length();
  54832. if (!(len === 0 || len === 1)) {
  54833. var num = 1.0 / len;
  54834. dir.x *= num;
  54835. dir.y *= num;
  54836. dir.z *= num;
  54837. result.length *= len;
  54838. }
  54839. };
  54840. Ray.smallnum = 0.00000001;
  54841. Ray.rayl = 10e8;
  54842. return Ray;
  54843. }());
  54844. BABYLON.Ray = Ray;
  54845. })(BABYLON || (BABYLON = {}));
  54846. //# sourceMappingURL=babylon.ray.js.map
  54847. var BABYLON;
  54848. (function (BABYLON) {
  54849. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54850. if (boxMin.x > sphereCenter.x + sphereRadius)
  54851. return false;
  54852. if (sphereCenter.x - sphereRadius > boxMax.x)
  54853. return false;
  54854. if (boxMin.y > sphereCenter.y + sphereRadius)
  54855. return false;
  54856. if (sphereCenter.y - sphereRadius > boxMax.y)
  54857. return false;
  54858. if (boxMin.z > sphereCenter.z + sphereRadius)
  54859. return false;
  54860. if (sphereCenter.z - sphereRadius > boxMax.z)
  54861. return false;
  54862. return true;
  54863. };
  54864. var getLowestRoot = (function () {
  54865. var result = { root: 0, found: false };
  54866. return function (a, b, c, maxR) {
  54867. result.root = 0;
  54868. result.found = false;
  54869. var determinant = b * b - 4.0 * a * c;
  54870. if (determinant < 0)
  54871. return result;
  54872. var sqrtD = Math.sqrt(determinant);
  54873. var r1 = (-b - sqrtD) / (2.0 * a);
  54874. var r2 = (-b + sqrtD) / (2.0 * a);
  54875. if (r1 > r2) {
  54876. var temp = r2;
  54877. r2 = r1;
  54878. r1 = temp;
  54879. }
  54880. if (r1 > 0 && r1 < maxR) {
  54881. result.root = r1;
  54882. result.found = true;
  54883. return result;
  54884. }
  54885. if (r2 > 0 && r2 < maxR) {
  54886. result.root = r2;
  54887. result.found = true;
  54888. return result;
  54889. }
  54890. return result;
  54891. };
  54892. })();
  54893. var Collider = /** @class */ (function () {
  54894. function Collider() {
  54895. this._collisionPoint = BABYLON.Vector3.Zero();
  54896. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54897. this._tempVector = BABYLON.Vector3.Zero();
  54898. this._tempVector2 = BABYLON.Vector3.Zero();
  54899. this._tempVector3 = BABYLON.Vector3.Zero();
  54900. this._tempVector4 = BABYLON.Vector3.Zero();
  54901. this._edge = BABYLON.Vector3.Zero();
  54902. this._baseToVertex = BABYLON.Vector3.Zero();
  54903. this._destinationPoint = BABYLON.Vector3.Zero();
  54904. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54905. this._displacementVector = BABYLON.Vector3.Zero();
  54906. /** @hidden */
  54907. this._radius = BABYLON.Vector3.One();
  54908. /** @hidden */
  54909. this._retry = 0;
  54910. /** @hidden */
  54911. this._basePointWorld = BABYLON.Vector3.Zero();
  54912. this._velocityWorld = BABYLON.Vector3.Zero();
  54913. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54914. this._collisionMask = -1;
  54915. }
  54916. Object.defineProperty(Collider.prototype, "collisionMask", {
  54917. get: function () {
  54918. return this._collisionMask;
  54919. },
  54920. set: function (mask) {
  54921. this._collisionMask = !isNaN(mask) ? mask : -1;
  54922. },
  54923. enumerable: true,
  54924. configurable: true
  54925. });
  54926. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54927. /**
  54928. * Gets the plane normal used to compute the sliding response (in local space)
  54929. */
  54930. get: function () {
  54931. return this._slidePlaneNormal;
  54932. },
  54933. enumerable: true,
  54934. configurable: true
  54935. });
  54936. // Methods
  54937. /** @hidden */
  54938. Collider.prototype._initialize = function (source, dir, e) {
  54939. this._velocity = dir;
  54940. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54941. this._basePoint = source;
  54942. source.multiplyToRef(this._radius, this._basePointWorld);
  54943. dir.multiplyToRef(this._radius, this._velocityWorld);
  54944. this._velocityWorldLength = this._velocityWorld.length();
  54945. this._epsilon = e;
  54946. this.collisionFound = false;
  54947. };
  54948. /** @hidden */
  54949. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54950. pa.subtractToRef(point, this._tempVector);
  54951. pb.subtractToRef(point, this._tempVector2);
  54952. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54953. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54954. if (d < 0)
  54955. return false;
  54956. pc.subtractToRef(point, this._tempVector3);
  54957. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54958. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54959. if (d < 0)
  54960. return false;
  54961. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54962. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54963. return d >= 0;
  54964. };
  54965. /** @hidden */
  54966. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54967. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54968. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54969. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54970. return false;
  54971. }
  54972. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54973. return false;
  54974. return true;
  54975. };
  54976. /** @hidden */
  54977. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54978. var t0;
  54979. var embeddedInPlane = false;
  54980. //defensive programming, actually not needed.
  54981. if (!trianglePlaneArray) {
  54982. trianglePlaneArray = [];
  54983. }
  54984. if (!trianglePlaneArray[faceIndex]) {
  54985. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54986. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54987. }
  54988. var trianglePlane = trianglePlaneArray[faceIndex];
  54989. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54990. return;
  54991. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54992. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54993. if (normalDotVelocity == 0) {
  54994. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54995. return;
  54996. embeddedInPlane = true;
  54997. t0 = 0;
  54998. }
  54999. else {
  55000. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55001. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55002. if (t0 > t1) {
  55003. var temp = t1;
  55004. t1 = t0;
  55005. t0 = temp;
  55006. }
  55007. if (t0 > 1.0 || t1 < 0.0)
  55008. return;
  55009. if (t0 < 0)
  55010. t0 = 0;
  55011. if (t0 > 1.0)
  55012. t0 = 1.0;
  55013. }
  55014. this._collisionPoint.copyFromFloats(0, 0, 0);
  55015. var found = false;
  55016. var t = 1.0;
  55017. if (!embeddedInPlane) {
  55018. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55019. this._velocity.scaleToRef(t0, this._tempVector);
  55020. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55021. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55022. found = true;
  55023. t = t0;
  55024. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55025. }
  55026. }
  55027. if (!found) {
  55028. var velocitySquaredLength = this._velocity.lengthSquared();
  55029. var a = velocitySquaredLength;
  55030. this._basePoint.subtractToRef(p1, this._tempVector);
  55031. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55032. var c = this._tempVector.lengthSquared() - 1.0;
  55033. var lowestRoot = getLowestRoot(a, b, c, t);
  55034. if (lowestRoot.found) {
  55035. t = lowestRoot.root;
  55036. found = true;
  55037. this._collisionPoint.copyFrom(p1);
  55038. }
  55039. this._basePoint.subtractToRef(p2, this._tempVector);
  55040. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55041. c = this._tempVector.lengthSquared() - 1.0;
  55042. lowestRoot = getLowestRoot(a, b, c, t);
  55043. if (lowestRoot.found) {
  55044. t = lowestRoot.root;
  55045. found = true;
  55046. this._collisionPoint.copyFrom(p2);
  55047. }
  55048. this._basePoint.subtractToRef(p3, this._tempVector);
  55049. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55050. c = this._tempVector.lengthSquared() - 1.0;
  55051. lowestRoot = getLowestRoot(a, b, c, t);
  55052. if (lowestRoot.found) {
  55053. t = lowestRoot.root;
  55054. found = true;
  55055. this._collisionPoint.copyFrom(p3);
  55056. }
  55057. p2.subtractToRef(p1, this._edge);
  55058. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55059. var edgeSquaredLength = this._edge.lengthSquared();
  55060. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55061. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55062. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55063. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55064. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55065. lowestRoot = getLowestRoot(a, b, c, t);
  55066. if (lowestRoot.found) {
  55067. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55068. if (f >= 0.0 && f <= 1.0) {
  55069. t = lowestRoot.root;
  55070. found = true;
  55071. this._edge.scaleInPlace(f);
  55072. p1.addToRef(this._edge, this._collisionPoint);
  55073. }
  55074. }
  55075. p3.subtractToRef(p2, this._edge);
  55076. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55077. edgeSquaredLength = this._edge.lengthSquared();
  55078. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55079. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55080. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55081. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55082. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55083. lowestRoot = getLowestRoot(a, b, c, t);
  55084. if (lowestRoot.found) {
  55085. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55086. if (f >= 0.0 && f <= 1.0) {
  55087. t = lowestRoot.root;
  55088. found = true;
  55089. this._edge.scaleInPlace(f);
  55090. p2.addToRef(this._edge, this._collisionPoint);
  55091. }
  55092. }
  55093. p1.subtractToRef(p3, this._edge);
  55094. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55095. edgeSquaredLength = this._edge.lengthSquared();
  55096. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55097. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55098. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55099. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55100. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55101. lowestRoot = getLowestRoot(a, b, c, t);
  55102. if (lowestRoot.found) {
  55103. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55104. if (f >= 0.0 && f <= 1.0) {
  55105. t = lowestRoot.root;
  55106. found = true;
  55107. this._edge.scaleInPlace(f);
  55108. p3.addToRef(this._edge, this._collisionPoint);
  55109. }
  55110. }
  55111. }
  55112. if (found) {
  55113. var distToCollision = t * this._velocity.length();
  55114. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55115. if (!this.intersectionPoint) {
  55116. this.intersectionPoint = this._collisionPoint.clone();
  55117. }
  55118. else {
  55119. this.intersectionPoint.copyFrom(this._collisionPoint);
  55120. }
  55121. this._nearestDistance = distToCollision;
  55122. this.collisionFound = true;
  55123. }
  55124. }
  55125. };
  55126. /** @hidden */
  55127. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55128. for (var i = indexStart; i < indexEnd; i += 3) {
  55129. var p1 = pts[indices[i] - decal];
  55130. var p2 = pts[indices[i + 1] - decal];
  55131. var p3 = pts[indices[i + 2] - decal];
  55132. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55133. }
  55134. };
  55135. /** @hidden */
  55136. Collider.prototype._getResponse = function (pos, vel) {
  55137. pos.addToRef(vel, this._destinationPoint);
  55138. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55139. this._basePoint.addToRef(vel, pos);
  55140. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55141. this._slidePlaneNormal.normalize();
  55142. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55143. pos.addInPlace(this._displacementVector);
  55144. this.intersectionPoint.addInPlace(this._displacementVector);
  55145. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55146. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55147. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55148. };
  55149. return Collider;
  55150. }());
  55151. BABYLON.Collider = Collider;
  55152. })(BABYLON || (BABYLON = {}));
  55153. //# sourceMappingURL=babylon.collider.js.map
  55154. var BABYLON;
  55155. (function (BABYLON) {
  55156. //WebWorker code will be inserted to this variable.
  55157. BABYLON.CollisionWorker = "";
  55158. /** Defines supported task for worker process */
  55159. var WorkerTaskType;
  55160. (function (WorkerTaskType) {
  55161. /** Initialization */
  55162. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55163. /** Update of geometry */
  55164. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55165. /** Evaluate collision */
  55166. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55167. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55168. /** Defines kind of replies returned by worker */
  55169. var WorkerReplyType;
  55170. (function (WorkerReplyType) {
  55171. /** Success */
  55172. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55173. /** Unkown error */
  55174. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55175. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55176. var CollisionCoordinatorWorker = /** @class */ (function () {
  55177. function CollisionCoordinatorWorker() {
  55178. var _this = this;
  55179. this._scaledPosition = BABYLON.Vector3.Zero();
  55180. this._scaledVelocity = BABYLON.Vector3.Zero();
  55181. this.onMeshUpdated = function (transformNode) {
  55182. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55183. };
  55184. this.onGeometryUpdated = function (geometry) {
  55185. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55186. };
  55187. this._afterRender = function () {
  55188. if (!_this._init)
  55189. return;
  55190. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55191. return;
  55192. }
  55193. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55194. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55195. if (_this._runningUpdated > 4) {
  55196. return;
  55197. }
  55198. ++_this._runningUpdated;
  55199. var payload = {
  55200. updatedMeshes: _this._addUpdateMeshesList,
  55201. updatedGeometries: _this._addUpdateGeometriesList,
  55202. removedGeometries: _this._toRemoveGeometryArray,
  55203. removedMeshes: _this._toRemoveMeshesArray
  55204. };
  55205. var message = {
  55206. payload: payload,
  55207. taskType: WorkerTaskType.UPDATE
  55208. };
  55209. var serializable = [];
  55210. for (var id in payload.updatedGeometries) {
  55211. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55212. //prepare transferables
  55213. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55214. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55215. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55216. }
  55217. }
  55218. _this._worker.postMessage(message, serializable);
  55219. _this._addUpdateMeshesList = {};
  55220. _this._addUpdateGeometriesList = {};
  55221. _this._toRemoveGeometryArray = [];
  55222. _this._toRemoveMeshesArray = [];
  55223. };
  55224. this._onMessageFromWorker = function (e) {
  55225. var returnData = e.data;
  55226. if (returnData.error != WorkerReplyType.SUCCESS) {
  55227. //TODO what errors can be returned from the worker?
  55228. BABYLON.Tools.Warn("error returned from worker!");
  55229. return;
  55230. }
  55231. switch (returnData.taskType) {
  55232. case WorkerTaskType.INIT:
  55233. _this._init = true;
  55234. //Update the worked with ALL of the scene's current state
  55235. _this._scene.meshes.forEach(function (mesh) {
  55236. _this.onMeshAdded(mesh);
  55237. });
  55238. _this._scene.getGeometries().forEach(function (geometry) {
  55239. _this.onGeometryAdded(geometry);
  55240. });
  55241. break;
  55242. case WorkerTaskType.UPDATE:
  55243. _this._runningUpdated--;
  55244. break;
  55245. case WorkerTaskType.COLLIDE:
  55246. var returnPayload = returnData.payload;
  55247. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55248. return;
  55249. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55250. if (callback) {
  55251. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55252. if (mesh) {
  55253. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55254. }
  55255. }
  55256. //cleanup
  55257. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55258. break;
  55259. }
  55260. };
  55261. this._collisionsCallbackArray = [];
  55262. this._init = false;
  55263. this._runningUpdated = 0;
  55264. this._addUpdateMeshesList = {};
  55265. this._addUpdateGeometriesList = {};
  55266. this._toRemoveGeometryArray = [];
  55267. this._toRemoveMeshesArray = [];
  55268. }
  55269. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55270. if (!this._init)
  55271. return;
  55272. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55273. return;
  55274. position.divideToRef(collider._radius, this._scaledPosition);
  55275. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55276. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55277. var payload = {
  55278. collider: {
  55279. position: this._scaledPosition.asArray(),
  55280. velocity: this._scaledVelocity.asArray(),
  55281. radius: collider._radius.asArray()
  55282. },
  55283. collisionId: collisionIndex,
  55284. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55285. maximumRetry: maximumRetry
  55286. };
  55287. var message = {
  55288. payload: payload,
  55289. taskType: WorkerTaskType.COLLIDE
  55290. };
  55291. this._worker.postMessage(message);
  55292. };
  55293. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55294. this._scene = scene;
  55295. this._scene.registerAfterRender(this._afterRender);
  55296. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55297. this._worker = new Worker(workerUrl);
  55298. this._worker.onmessage = this._onMessageFromWorker;
  55299. var message = {
  55300. payload: {},
  55301. taskType: WorkerTaskType.INIT
  55302. };
  55303. this._worker.postMessage(message);
  55304. };
  55305. CollisionCoordinatorWorker.prototype.destroy = function () {
  55306. this._scene.unregisterAfterRender(this._afterRender);
  55307. this._worker.terminate();
  55308. };
  55309. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55310. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55311. this.onMeshUpdated(mesh);
  55312. };
  55313. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55314. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55315. };
  55316. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55317. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55318. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55319. this.onGeometryUpdated(geometry);
  55320. };
  55321. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55322. this._toRemoveGeometryArray.push(geometry.id);
  55323. };
  55324. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55325. var submeshes = [];
  55326. if (mesh.subMeshes) {
  55327. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55328. var boundingInfo = sm.getBoundingInfo();
  55329. return {
  55330. position: idx,
  55331. verticesStart: sm.verticesStart,
  55332. verticesCount: sm.verticesCount,
  55333. indexStart: sm.indexStart,
  55334. indexCount: sm.indexCount,
  55335. hasMaterial: !!sm.getMaterial(),
  55336. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55337. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55338. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55339. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55340. };
  55341. });
  55342. }
  55343. var geometryId = null;
  55344. if (mesh instanceof BABYLON.Mesh) {
  55345. var geometry = mesh.geometry;
  55346. geometryId = geometry ? geometry.id : null;
  55347. }
  55348. else if (mesh instanceof BABYLON.InstancedMesh) {
  55349. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55350. geometryId = geometry ? geometry.id : null;
  55351. }
  55352. var boundingInfo = mesh.getBoundingInfo();
  55353. return {
  55354. uniqueId: mesh.uniqueId,
  55355. id: mesh.id,
  55356. name: mesh.name,
  55357. geometryId: geometryId,
  55358. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55359. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55360. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55361. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55362. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55363. subMeshes: submeshes,
  55364. checkCollisions: mesh.checkCollisions
  55365. };
  55366. };
  55367. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55368. return {
  55369. id: geometry.id,
  55370. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55371. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55372. indices: new Uint32Array(geometry.getIndices() || []),
  55373. };
  55374. };
  55375. return CollisionCoordinatorWorker;
  55376. }());
  55377. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55378. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55379. function CollisionCoordinatorLegacy() {
  55380. this._scaledPosition = BABYLON.Vector3.Zero();
  55381. this._scaledVelocity = BABYLON.Vector3.Zero();
  55382. this._finalPosition = BABYLON.Vector3.Zero();
  55383. }
  55384. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55385. position.divideToRef(collider._radius, this._scaledPosition);
  55386. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55387. collider.collidedMesh = null;
  55388. collider._retry = 0;
  55389. collider._initialVelocity = this._scaledVelocity;
  55390. collider._initialPosition = this._scaledPosition;
  55391. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55392. this._finalPosition.multiplyInPlace(collider._radius);
  55393. //run the callback
  55394. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55395. };
  55396. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55397. this._scene = scene;
  55398. };
  55399. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55400. //Legacy need no destruction method.
  55401. };
  55402. //No update in legacy mode
  55403. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55404. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55405. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55406. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55407. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55408. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55409. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55410. if (excludedMesh === void 0) { excludedMesh = null; }
  55411. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55412. if (collider._retry >= maximumRetry) {
  55413. finalPosition.copyFrom(position);
  55414. return;
  55415. }
  55416. // Check if this is a mesh else camera or -1
  55417. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55418. collider._initialize(position, velocity, closeDistance);
  55419. // Check all meshes
  55420. for (var index = 0; index < this._scene.meshes.length; index++) {
  55421. var mesh = this._scene.meshes[index];
  55422. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55423. mesh._checkCollision(collider);
  55424. }
  55425. }
  55426. if (!collider.collisionFound) {
  55427. position.addToRef(velocity, finalPosition);
  55428. return;
  55429. }
  55430. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55431. collider._getResponse(position, velocity);
  55432. }
  55433. if (velocity.length() <= closeDistance) {
  55434. finalPosition.copyFrom(position);
  55435. return;
  55436. }
  55437. collider._retry++;
  55438. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55439. };
  55440. return CollisionCoordinatorLegacy;
  55441. }());
  55442. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55443. })(BABYLON || (BABYLON = {}));
  55444. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55445. var BABYLON;
  55446. (function (BABYLON) {
  55447. /**
  55448. * A particle represents one of the element emitted by a particle system.
  55449. * This is mainly define by its coordinates, direction, velocity and age.
  55450. */
  55451. var Particle = /** @class */ (function () {
  55452. /**
  55453. * Creates a new instance Particle
  55454. * @param particleSystem the particle system the particle belongs to
  55455. */
  55456. function Particle(
  55457. /**
  55458. * The particle system the particle belongs to.
  55459. */
  55460. particleSystem) {
  55461. this.particleSystem = particleSystem;
  55462. /**
  55463. * The world position of the particle in the scene.
  55464. */
  55465. this.position = BABYLON.Vector3.Zero();
  55466. /**
  55467. * The world direction of the particle in the scene.
  55468. */
  55469. this.direction = BABYLON.Vector3.Zero();
  55470. /**
  55471. * The color of the particle.
  55472. */
  55473. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55474. /**
  55475. * The color change of the particle per step.
  55476. */
  55477. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55478. /**
  55479. * Defines how long will the life of the particle be.
  55480. */
  55481. this.lifeTime = 1.0;
  55482. /**
  55483. * The current age of the particle.
  55484. */
  55485. this.age = 0;
  55486. /**
  55487. * The current size of the particle.
  55488. */
  55489. this.size = 0;
  55490. /**
  55491. * The current scale of the particle.
  55492. */
  55493. this.scale = new BABYLON.Vector2(1, 1);
  55494. /**
  55495. * The current angle of the particle.
  55496. */
  55497. this.angle = 0;
  55498. /**
  55499. * Defines how fast is the angle changing.
  55500. */
  55501. this.angularSpeed = 0;
  55502. /**
  55503. * Defines the cell index used by the particle to be rendered from a sprite.
  55504. */
  55505. this.cellIndex = 0;
  55506. /** @hidden */
  55507. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55508. /** @hidden */
  55509. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55510. /** @hidden */
  55511. this._currentSize1 = 0;
  55512. /** @hidden */
  55513. this._currentSize2 = 0;
  55514. /** @hidden */
  55515. this._currentAngularSpeed1 = 0;
  55516. /** @hidden */
  55517. this._currentAngularSpeed2 = 0;
  55518. /** @hidden */
  55519. this._currentVelocity1 = 0;
  55520. /** @hidden */
  55521. this._currentVelocity2 = 0;
  55522. /** @hidden */
  55523. this._currentLimitVelocity1 = 0;
  55524. /** @hidden */
  55525. this._currentLimitVelocity2 = 0;
  55526. /** @hidden */
  55527. this._currentDrag1 = 0;
  55528. /** @hidden */
  55529. this._currentDrag2 = 0;
  55530. if (!this.particleSystem.isAnimationSheetEnabled) {
  55531. return;
  55532. }
  55533. this.updateCellInfoFromSystem();
  55534. }
  55535. Particle.prototype.updateCellInfoFromSystem = function () {
  55536. this.cellIndex = this.particleSystem.startSpriteCellID;
  55537. };
  55538. /**
  55539. * Defines how the sprite cell index is updated for the particle
  55540. */
  55541. Particle.prototype.updateCellIndex = function () {
  55542. var offsetAge = this.age;
  55543. if (this.particleSystem.spriteRandomStartCell) {
  55544. if (this._randomCellOffset === undefined) {
  55545. this._randomCellOffset = Math.random() * this.lifeTime;
  55546. }
  55547. offsetAge += this._randomCellOffset;
  55548. }
  55549. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55550. var ratio = BABYLON.Scalar.Clamp(((offsetAge * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55551. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55552. };
  55553. /** @hidden */
  55554. Particle.prototype._reset = function () {
  55555. this.age = 0;
  55556. this._currentColorGradient = null;
  55557. this._currentSizeGradient = null;
  55558. this._currentAngularSpeedGradient = null;
  55559. this._currentVelocityGradient = null;
  55560. this._currentLimitVelocityGradient = null;
  55561. this._currentDragGradient = null;
  55562. this.cellIndex = this.particleSystem.startSpriteCellID;
  55563. this._randomCellOffset = undefined;
  55564. };
  55565. /**
  55566. * Copy the properties of particle to another one.
  55567. * @param other the particle to copy the information to.
  55568. */
  55569. Particle.prototype.copyTo = function (other) {
  55570. other.position.copyFrom(this.position);
  55571. if (this._initialDirection) {
  55572. if (other._initialDirection) {
  55573. other._initialDirection.copyFrom(this._initialDirection);
  55574. }
  55575. else {
  55576. other._initialDirection = this._initialDirection.clone();
  55577. }
  55578. }
  55579. else {
  55580. other._initialDirection = null;
  55581. }
  55582. other.direction.copyFrom(this.direction);
  55583. other.color.copyFrom(this.color);
  55584. other.colorStep.copyFrom(this.colorStep);
  55585. other.lifeTime = this.lifeTime;
  55586. other.age = this.age;
  55587. other._randomCellOffset = undefined;
  55588. other.size = this.size;
  55589. other.scale.copyFrom(this.scale);
  55590. other.angle = this.angle;
  55591. other.angularSpeed = this.angularSpeed;
  55592. other.particleSystem = this.particleSystem;
  55593. other.cellIndex = this.cellIndex;
  55594. if (this._currentColorGradient) {
  55595. other._currentColorGradient = this._currentColorGradient;
  55596. other._currentColor1.copyFrom(this._currentColor1);
  55597. other._currentColor2.copyFrom(this._currentColor2);
  55598. }
  55599. if (this._currentSizeGradient) {
  55600. other._currentSizeGradient = this._currentSizeGradient;
  55601. other._currentSize1 = this._currentSize1;
  55602. other._currentSize2 = this._currentSize2;
  55603. }
  55604. if (this._currentAngularSpeedGradient) {
  55605. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55606. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55607. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55608. }
  55609. if (this._currentVelocityGradient) {
  55610. other._currentVelocityGradient = this._currentVelocityGradient;
  55611. other._currentVelocity1 = this._currentVelocity1;
  55612. other._currentVelocity2 = this._currentVelocity2;
  55613. }
  55614. if (this._currentLimitVelocityGradient) {
  55615. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55616. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55617. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55618. }
  55619. if (this._currentDragGradient) {
  55620. other._currentDragGradient = this._currentDragGradient;
  55621. other._currentDrag1 = this._currentDrag1;
  55622. other._currentDrag2 = this._currentDrag2;
  55623. }
  55624. if (this.particleSystem.isAnimationSheetEnabled) {
  55625. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55626. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55627. }
  55628. };
  55629. return Particle;
  55630. }());
  55631. BABYLON.Particle = Particle;
  55632. })(BABYLON || (BABYLON = {}));
  55633. //# sourceMappingURL=babylon.particle.js.map
  55634. var BABYLON;
  55635. (function (BABYLON) {
  55636. /**
  55637. * This represents the base class for particle system in Babylon.
  55638. * 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.
  55639. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55640. * @example https://doc.babylonjs.com/babylon101/particles
  55641. */
  55642. var BaseParticleSystem = /** @class */ (function () {
  55643. /**
  55644. * Instantiates a particle system.
  55645. * 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.
  55646. * @param name The name of the particle system
  55647. */
  55648. function BaseParticleSystem(name) {
  55649. /**
  55650. * List of animations used by the particle system.
  55651. */
  55652. this.animations = [];
  55653. /**
  55654. * The rendering group used by the Particle system to chose when to render.
  55655. */
  55656. this.renderingGroupId = 0;
  55657. /**
  55658. * The emitter represents the Mesh or position we are attaching the particle system to.
  55659. */
  55660. this.emitter = null;
  55661. /**
  55662. * The maximum number of particles to emit per frame
  55663. */
  55664. this.emitRate = 10;
  55665. /**
  55666. * If you want to launch only a few particles at once, that can be done, as well.
  55667. */
  55668. this.manualEmitCount = -1;
  55669. /**
  55670. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55671. */
  55672. this.updateSpeed = 0.01;
  55673. /**
  55674. * The amount of time the particle system is running (depends of the overall update speed).
  55675. */
  55676. this.targetStopDuration = 0;
  55677. /**
  55678. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55679. */
  55680. this.disposeOnStop = false;
  55681. /**
  55682. * Minimum power of emitting particles.
  55683. */
  55684. this.minEmitPower = 1;
  55685. /**
  55686. * Maximum power of emitting particles.
  55687. */
  55688. this.maxEmitPower = 1;
  55689. /**
  55690. * Minimum life time of emitting particles.
  55691. */
  55692. this.minLifeTime = 1;
  55693. /**
  55694. * Maximum life time of emitting particles.
  55695. */
  55696. this.maxLifeTime = 1;
  55697. /**
  55698. * Minimum Size of emitting particles.
  55699. */
  55700. this.minSize = 1;
  55701. /**
  55702. * Maximum Size of emitting particles.
  55703. */
  55704. this.maxSize = 1;
  55705. /**
  55706. * Minimum scale of emitting particles on X axis.
  55707. */
  55708. this.minScaleX = 1;
  55709. /**
  55710. * Maximum scale of emitting particles on X axis.
  55711. */
  55712. this.maxScaleX = 1;
  55713. /**
  55714. * Minimum scale of emitting particles on Y axis.
  55715. */
  55716. this.minScaleY = 1;
  55717. /**
  55718. * Maximum scale of emitting particles on Y axis.
  55719. */
  55720. this.maxScaleY = 1;
  55721. /**
  55722. * Gets or sets the minimal initial rotation in radians.
  55723. */
  55724. this.minInitialRotation = 0;
  55725. /**
  55726. * Gets or sets the maximal initial rotation in radians.
  55727. */
  55728. this.maxInitialRotation = 0;
  55729. /**
  55730. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55731. */
  55732. this.minAngularSpeed = 0;
  55733. /**
  55734. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55735. */
  55736. this.maxAngularSpeed = 0;
  55737. /**
  55738. * The layer mask we are rendering the particles through.
  55739. */
  55740. this.layerMask = 0x0FFFFFFF;
  55741. /**
  55742. * This can help using your own shader to render the particle system.
  55743. * The according effect will be created
  55744. */
  55745. this.customShader = null;
  55746. /**
  55747. * By default particle system starts as soon as they are created. This prevents the
  55748. * automatic start to happen and let you decide when to start emitting particles.
  55749. */
  55750. this.preventAutoStart = false;
  55751. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55752. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55753. /**
  55754. * Callback triggered when the particle animation is ending.
  55755. */
  55756. this.onAnimationEnd = null;
  55757. /**
  55758. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55759. */
  55760. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55761. /**
  55762. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55763. * to override the particles.
  55764. */
  55765. this.forceDepthWrite = false;
  55766. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55767. this.preWarmCycles = 0;
  55768. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55769. this.preWarmStepOffset = 1;
  55770. /**
  55771. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55772. */
  55773. this.spriteCellChangeSpeed = 1;
  55774. /**
  55775. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55776. */
  55777. this.startSpriteCellID = 0;
  55778. /**
  55779. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55780. */
  55781. this.endSpriteCellID = 0;
  55782. /**
  55783. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55784. */
  55785. this.spriteCellWidth = 0;
  55786. /**
  55787. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55788. */
  55789. this.spriteCellHeight = 0;
  55790. /**
  55791. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55792. */
  55793. this.spriteRandomStartCell = false;
  55794. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55795. this.translationPivot = new BABYLON.Vector2(0, 0);
  55796. /**
  55797. * You can use gravity if you want to give an orientation to your particles.
  55798. */
  55799. this.gravity = BABYLON.Vector3.Zero();
  55800. this._colorGradients = null;
  55801. this._sizeGradients = null;
  55802. this._lifeTimeGradients = null;
  55803. this._angularSpeedGradients = null;
  55804. this._velocityGradients = null;
  55805. this._limitVelocityGradients = null;
  55806. this._dragGradients = null;
  55807. this._emitRateGradients = null;
  55808. this._startSizeGradients = null;
  55809. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55810. this.limitVelocityDamping = 0.4;
  55811. /**
  55812. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55813. */
  55814. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55815. /**
  55816. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55817. */
  55818. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55819. /**
  55820. * Color the particle will have at the end of its lifetime
  55821. */
  55822. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55823. /**
  55824. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55825. */
  55826. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55827. /**
  55828. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55829. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55830. */
  55831. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55832. this._isBillboardBased = true;
  55833. /**
  55834. * Local cache of defines for image processing.
  55835. */
  55836. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55837. this.id = name;
  55838. this.name = name;
  55839. }
  55840. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55841. /**
  55842. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55843. */
  55844. get: function () {
  55845. return this._isAnimationSheetEnabled;
  55846. },
  55847. set: function (value) {
  55848. if (this._isAnimationSheetEnabled == value) {
  55849. return;
  55850. }
  55851. this._isAnimationSheetEnabled = value;
  55852. this._reset();
  55853. },
  55854. enumerable: true,
  55855. configurable: true
  55856. });
  55857. /**
  55858. * Get hosting scene
  55859. * @returns the scene
  55860. */
  55861. BaseParticleSystem.prototype.getScene = function () {
  55862. return this._scene;
  55863. };
  55864. /**
  55865. * Gets the current list of drag gradients.
  55866. * You must use addDragGradient and removeDragGradient to udpate this list
  55867. * @returns the list of drag gradients
  55868. */
  55869. BaseParticleSystem.prototype.getDragGradients = function () {
  55870. return this._dragGradients;
  55871. };
  55872. /**
  55873. * Gets the current list of limit velocity gradients.
  55874. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55875. * @returns the list of limit velocity gradients
  55876. */
  55877. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55878. return this._limitVelocityGradients;
  55879. };
  55880. /**
  55881. * Gets the current list of color gradients.
  55882. * You must use addColorGradient and removeColorGradient to udpate this list
  55883. * @returns the list of color gradients
  55884. */
  55885. BaseParticleSystem.prototype.getColorGradients = function () {
  55886. return this._colorGradients;
  55887. };
  55888. /**
  55889. * Gets the current list of size gradients.
  55890. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55891. * @returns the list of size gradients
  55892. */
  55893. BaseParticleSystem.prototype.getSizeGradients = function () {
  55894. return this._sizeGradients;
  55895. };
  55896. /**
  55897. * Gets the current list of life time gradients.
  55898. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55899. * @returns the list of life time gradients
  55900. */
  55901. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55902. return this._lifeTimeGradients;
  55903. };
  55904. /**
  55905. * Gets the current list of angular speed gradients.
  55906. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55907. * @returns the list of angular speed gradients
  55908. */
  55909. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55910. return this._angularSpeedGradients;
  55911. };
  55912. /**
  55913. * Gets the current list of velocity gradients.
  55914. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55915. * @returns the list of velocity gradients
  55916. */
  55917. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55918. return this._velocityGradients;
  55919. };
  55920. /**
  55921. * Gets the current list of start size gradients.
  55922. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55923. * @returns the list of start size gradients
  55924. */
  55925. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55926. return this._startSizeGradients;
  55927. };
  55928. /**
  55929. * Gets the current list of emit rate gradients.
  55930. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55931. * @returns the list of emit rate gradients
  55932. */
  55933. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55934. return this._emitRateGradients;
  55935. };
  55936. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55937. /**
  55938. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55939. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55940. */
  55941. get: function () {
  55942. if (this.particleEmitterType.direction1) {
  55943. return this.particleEmitterType.direction1;
  55944. }
  55945. return BABYLON.Vector3.Zero();
  55946. },
  55947. set: function (value) {
  55948. if (this.particleEmitterType.direction1) {
  55949. this.particleEmitterType.direction1 = value;
  55950. }
  55951. },
  55952. enumerable: true,
  55953. configurable: true
  55954. });
  55955. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55956. /**
  55957. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55958. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55959. */
  55960. get: function () {
  55961. if (this.particleEmitterType.direction2) {
  55962. return this.particleEmitterType.direction2;
  55963. }
  55964. return BABYLON.Vector3.Zero();
  55965. },
  55966. set: function (value) {
  55967. if (this.particleEmitterType.direction2) {
  55968. this.particleEmitterType.direction2 = value;
  55969. }
  55970. },
  55971. enumerable: true,
  55972. configurable: true
  55973. });
  55974. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55975. /**
  55976. * 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.
  55977. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55978. */
  55979. get: function () {
  55980. if (this.particleEmitterType.minEmitBox) {
  55981. return this.particleEmitterType.minEmitBox;
  55982. }
  55983. return BABYLON.Vector3.Zero();
  55984. },
  55985. set: function (value) {
  55986. if (this.particleEmitterType.minEmitBox) {
  55987. this.particleEmitterType.minEmitBox = value;
  55988. }
  55989. },
  55990. enumerable: true,
  55991. configurable: true
  55992. });
  55993. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55994. /**
  55995. * 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.
  55996. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55997. */
  55998. get: function () {
  55999. if (this.particleEmitterType.maxEmitBox) {
  56000. return this.particleEmitterType.maxEmitBox;
  56001. }
  56002. return BABYLON.Vector3.Zero();
  56003. },
  56004. set: function (value) {
  56005. if (this.particleEmitterType.maxEmitBox) {
  56006. this.particleEmitterType.maxEmitBox = value;
  56007. }
  56008. },
  56009. enumerable: true,
  56010. configurable: true
  56011. });
  56012. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56013. /**
  56014. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56015. */
  56016. get: function () {
  56017. return this._isBillboardBased;
  56018. },
  56019. set: function (value) {
  56020. if (this._isBillboardBased === value) {
  56021. return;
  56022. }
  56023. this._isBillboardBased = value;
  56024. this._reset();
  56025. },
  56026. enumerable: true,
  56027. configurable: true
  56028. });
  56029. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56030. /**
  56031. * Gets the image processing configuration used either in this material.
  56032. */
  56033. get: function () {
  56034. return this._imageProcessingConfiguration;
  56035. },
  56036. /**
  56037. * Sets the Default image processing configuration used either in the this material.
  56038. *
  56039. * If sets to null, the scene one is in use.
  56040. */
  56041. set: function (value) {
  56042. this._attachImageProcessingConfiguration(value);
  56043. },
  56044. enumerable: true,
  56045. configurable: true
  56046. });
  56047. /**
  56048. * Attaches a new image processing configuration to the Standard Material.
  56049. * @param configuration
  56050. */
  56051. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56052. if (configuration === this._imageProcessingConfiguration) {
  56053. return;
  56054. }
  56055. // Pick the scene configuration if needed.
  56056. if (!configuration) {
  56057. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56058. }
  56059. else {
  56060. this._imageProcessingConfiguration = configuration;
  56061. }
  56062. };
  56063. /** @hidden */
  56064. BaseParticleSystem.prototype._reset = function () {
  56065. };
  56066. /**
  56067. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56068. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56069. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56070. * @returns the emitter
  56071. */
  56072. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56073. var particleEmitter = new BABYLON.PointParticleEmitter();
  56074. particleEmitter.direction1 = direction1;
  56075. particleEmitter.direction2 = direction2;
  56076. this.particleEmitterType = particleEmitter;
  56077. return particleEmitter;
  56078. };
  56079. /**
  56080. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56081. * @param radius The radius of the hemisphere to emit from
  56082. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56083. * @returns the emitter
  56084. */
  56085. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56086. if (radius === void 0) { radius = 1; }
  56087. if (radiusRange === void 0) { radiusRange = 1; }
  56088. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56089. this.particleEmitterType = particleEmitter;
  56090. return particleEmitter;
  56091. };
  56092. /**
  56093. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56094. * @param radius The radius of the sphere to emit from
  56095. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56096. * @returns the emitter
  56097. */
  56098. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56099. if (radius === void 0) { radius = 1; }
  56100. if (radiusRange === void 0) { radiusRange = 1; }
  56101. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56102. this.particleEmitterType = particleEmitter;
  56103. return particleEmitter;
  56104. };
  56105. /**
  56106. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56107. * @param radius The radius of the sphere to emit from
  56108. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56109. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56110. * @returns the emitter
  56111. */
  56112. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56113. if (radius === void 0) { radius = 1; }
  56114. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56115. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56116. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56117. this.particleEmitterType = particleEmitter;
  56118. return particleEmitter;
  56119. };
  56120. /**
  56121. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56122. * @param radius The radius of the emission cylinder
  56123. * @param height The height of the emission cylinder
  56124. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56125. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56126. * @returns the emitter
  56127. */
  56128. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56129. if (radius === void 0) { radius = 1; }
  56130. if (height === void 0) { height = 1; }
  56131. if (radiusRange === void 0) { radiusRange = 1; }
  56132. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56133. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56134. this.particleEmitterType = particleEmitter;
  56135. return particleEmitter;
  56136. };
  56137. /**
  56138. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56139. * @param radius The radius of the cylinder to emit from
  56140. * @param height The height of the emission cylinder
  56141. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56142. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56143. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56144. * @returns the emitter
  56145. */
  56146. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56147. if (radius === void 0) { radius = 1; }
  56148. if (height === void 0) { height = 1; }
  56149. if (radiusRange === void 0) { radiusRange = 1; }
  56150. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56151. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56152. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56153. this.particleEmitterType = particleEmitter;
  56154. return particleEmitter;
  56155. };
  56156. /**
  56157. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56158. * @param radius The radius of the cone to emit from
  56159. * @param angle The base angle of the cone
  56160. * @returns the emitter
  56161. */
  56162. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56163. if (radius === void 0) { radius = 1; }
  56164. if (angle === void 0) { angle = Math.PI / 4; }
  56165. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56166. this.particleEmitterType = particleEmitter;
  56167. return particleEmitter;
  56168. };
  56169. /**
  56170. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56171. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56172. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56173. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56174. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56175. * @returns the emitter
  56176. */
  56177. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56178. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56179. this.particleEmitterType = particleEmitter;
  56180. this.direction1 = direction1;
  56181. this.direction2 = direction2;
  56182. this.minEmitBox = minEmitBox;
  56183. this.maxEmitBox = maxEmitBox;
  56184. return particleEmitter;
  56185. };
  56186. /**
  56187. * Source color is added to the destination color without alpha affecting the result.
  56188. */
  56189. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56190. /**
  56191. * Blend current color and particle color using particle’s alpha.
  56192. */
  56193. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56194. /**
  56195. * Add current color and particle color multiplied by particle’s alpha.
  56196. */
  56197. BaseParticleSystem.BLENDMODE_ADD = 2;
  56198. /**
  56199. * Multiply current color with particle color
  56200. */
  56201. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56202. return BaseParticleSystem;
  56203. }());
  56204. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56205. })(BABYLON || (BABYLON = {}));
  56206. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56207. var BABYLON;
  56208. (function (BABYLON) {
  56209. /**
  56210. * This represents a particle system in Babylon.
  56211. * 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.
  56212. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56213. * @example https://doc.babylonjs.com/babylon101/particles
  56214. */
  56215. var ParticleSystem = /** @class */ (function (_super) {
  56216. __extends(ParticleSystem, _super);
  56217. /**
  56218. * Instantiates a particle system.
  56219. * 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.
  56220. * @param name The name of the particle system
  56221. * @param capacity The max number of particles alive at the same time
  56222. * @param scene The scene the particle system belongs to
  56223. * @param customEffect a custom effect used to change the way particles are rendered by default
  56224. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56225. * @param epsilon Offset used to render the particles
  56226. */
  56227. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56228. if (customEffect === void 0) { customEffect = null; }
  56229. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56230. if (epsilon === void 0) { epsilon = 0.01; }
  56231. var _this = _super.call(this, name) || this;
  56232. /**
  56233. * An event triggered when the system is disposed
  56234. */
  56235. _this.onDisposeObservable = new BABYLON.Observable();
  56236. _this._particles = new Array();
  56237. _this._stockParticles = new Array();
  56238. _this._newPartsExcess = 0;
  56239. _this._vertexBuffers = {};
  56240. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56241. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56242. _this._scaledDirection = BABYLON.Vector3.Zero();
  56243. _this._scaledGravity = BABYLON.Vector3.Zero();
  56244. _this._currentRenderId = -1;
  56245. _this._useInstancing = false;
  56246. _this._started = false;
  56247. _this._stopped = false;
  56248. _this._actualFrame = 0;
  56249. /** @hidden */
  56250. _this._currentEmitRate1 = 0;
  56251. /** @hidden */
  56252. _this._currentEmitRate2 = 0;
  56253. /** @hidden */
  56254. _this._currentStartSize1 = 0;
  56255. /** @hidden */
  56256. _this._currentStartSize2 = 0;
  56257. // start of sub system methods
  56258. /**
  56259. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56260. * Its lifetime will start back at 0.
  56261. */
  56262. _this.recycleParticle = function (particle) {
  56263. var lastParticle = _this._particles.pop();
  56264. if (lastParticle !== particle) {
  56265. lastParticle.copyTo(particle);
  56266. }
  56267. _this._stockParticles.push(lastParticle);
  56268. };
  56269. _this._createParticle = function () {
  56270. var particle;
  56271. if (_this._stockParticles.length !== 0) {
  56272. particle = _this._stockParticles.pop();
  56273. particle._reset();
  56274. }
  56275. else {
  56276. particle = new BABYLON.Particle(_this);
  56277. }
  56278. return particle;
  56279. };
  56280. _this._emitFromParticle = function (particle) {
  56281. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56282. return;
  56283. }
  56284. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56285. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56286. subSystem._rootParticleSystem = _this;
  56287. _this.activeSubSystems.push(subSystem);
  56288. subSystem.start();
  56289. };
  56290. _this._capacity = capacity;
  56291. _this._epsilon = epsilon;
  56292. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56293. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56294. // Setup the default processing configuration to the scene.
  56295. _this._attachImageProcessingConfiguration(null);
  56296. _this._customEffect = customEffect;
  56297. _this._scene.particleSystems.push(_this);
  56298. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56299. _this._createIndexBuffer();
  56300. _this._createVertexBuffers();
  56301. // Default emitter type
  56302. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56303. _this.updateFunction = function (particles) {
  56304. var noiseTextureData = null;
  56305. var noiseTextureSize = null;
  56306. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56307. noiseTextureData = (_this.noiseTexture.readPixels());
  56308. noiseTextureSize = _this.noiseTexture.getSize();
  56309. }
  56310. var _loop_1 = function () {
  56311. particle = particles[index];
  56312. particle.age += _this._scaledUpdateSpeed;
  56313. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56314. _this._emitFromParticle(particle);
  56315. _this.recycleParticle(particle);
  56316. index--;
  56317. return "continue";
  56318. }
  56319. else {
  56320. var ratio = particle.age / particle.lifeTime;
  56321. // Color
  56322. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56323. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56324. if (currentGradient !== particle._currentColorGradient) {
  56325. particle._currentColor1.copyFrom(particle._currentColor2);
  56326. nextGradient.getColorToRef(particle._currentColor2);
  56327. particle._currentColorGradient = currentGradient;
  56328. }
  56329. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56330. });
  56331. }
  56332. else {
  56333. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56334. particle.color.addInPlace(_this._scaledColorStep);
  56335. if (particle.color.a < 0) {
  56336. particle.color.a = 0;
  56337. }
  56338. }
  56339. // Angular speed
  56340. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56341. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56342. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56343. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56344. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56345. particle._currentAngularSpeedGradient = currentGradient;
  56346. }
  56347. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56348. });
  56349. }
  56350. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56351. // Direction
  56352. var directionScale_1 = _this._scaledUpdateSpeed;
  56353. /// Velocity
  56354. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56355. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56356. if (currentGradient !== particle._currentVelocityGradient) {
  56357. particle._currentVelocity1 = particle._currentVelocity2;
  56358. particle._currentVelocity2 = nextGradient.getFactor();
  56359. particle._currentVelocityGradient = currentGradient;
  56360. }
  56361. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56362. });
  56363. }
  56364. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56365. /// Limit velocity
  56366. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56367. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56368. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56369. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56370. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56371. particle._currentLimitVelocityGradient = currentGradient;
  56372. }
  56373. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56374. var currentVelocity = particle.direction.length();
  56375. if (currentVelocity > limitVelocity) {
  56376. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56377. }
  56378. });
  56379. }
  56380. /// Drag
  56381. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56382. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56383. if (currentGradient !== particle._currentDragGradient) {
  56384. particle._currentDrag1 = particle._currentDrag2;
  56385. particle._currentDrag2 = nextGradient.getFactor();
  56386. particle._currentDragGradient = currentGradient;
  56387. }
  56388. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56389. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56390. });
  56391. }
  56392. particle.position.addInPlace(_this._scaledDirection);
  56393. // Noise
  56394. if (noiseTextureData && noiseTextureSize) {
  56395. var localPosition = BABYLON.Tmp.Vector3[0];
  56396. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56397. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56398. particle.position.subtractToRef(emitterPosition, localPosition);
  56399. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56400. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56401. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56402. var force = BABYLON.Tmp.Vector3[0];
  56403. var scaledForce = BABYLON.Tmp.Vector3[1];
  56404. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56405. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56406. particle.direction.addInPlace(scaledForce);
  56407. }
  56408. // Gravity
  56409. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56410. particle.direction.addInPlace(_this._scaledGravity);
  56411. // Size
  56412. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56413. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56414. if (currentGradient !== particle._currentSizeGradient) {
  56415. particle._currentSize1 = particle._currentSize2;
  56416. particle._currentSize2 = nextGradient.getFactor();
  56417. particle._currentSizeGradient = currentGradient;
  56418. }
  56419. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56420. });
  56421. }
  56422. if (_this._isAnimationSheetEnabled) {
  56423. particle.updateCellIndex();
  56424. }
  56425. }
  56426. };
  56427. var particle;
  56428. for (var index = 0; index < particles.length; index++) {
  56429. _loop_1();
  56430. }
  56431. };
  56432. return _this;
  56433. }
  56434. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56435. /**
  56436. * Sets a callback that will be triggered when the system is disposed
  56437. */
  56438. set: function (callback) {
  56439. if (this._onDisposeObserver) {
  56440. this.onDisposeObservable.remove(this._onDisposeObserver);
  56441. }
  56442. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56443. },
  56444. enumerable: true,
  56445. configurable: true
  56446. });
  56447. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56448. //end of Sub-emitter
  56449. /**
  56450. * Gets the current list of active particles
  56451. */
  56452. get: function () {
  56453. return this._particles;
  56454. },
  56455. enumerable: true,
  56456. configurable: true
  56457. });
  56458. /**
  56459. * Returns the string "ParticleSystem"
  56460. * @returns a string containing the class name
  56461. */
  56462. ParticleSystem.prototype.getClassName = function () {
  56463. return "ParticleSystem";
  56464. };
  56465. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56466. var newGradient = new BABYLON.FactorGradient();
  56467. newGradient.gradient = gradient;
  56468. newGradient.factor1 = factor;
  56469. newGradient.factor2 = factor2;
  56470. factorGradients.push(newGradient);
  56471. factorGradients.sort(function (a, b) {
  56472. if (a.gradient < b.gradient) {
  56473. return -1;
  56474. }
  56475. else if (a.gradient > b.gradient) {
  56476. return 1;
  56477. }
  56478. return 0;
  56479. });
  56480. };
  56481. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56482. if (!factorGradients) {
  56483. return;
  56484. }
  56485. var index = 0;
  56486. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56487. var factorGradient = factorGradients_1[_i];
  56488. if (factorGradient.gradient === gradient) {
  56489. factorGradients.splice(index, 1);
  56490. break;
  56491. }
  56492. index++;
  56493. }
  56494. };
  56495. /**
  56496. * Adds a new life time gradient
  56497. * @param gradient defines the gradient to use (between 0 and 1)
  56498. * @param factor defines the life time factor to affect to the specified gradient
  56499. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56500. * @returns the current particle system
  56501. */
  56502. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56503. if (!this._lifeTimeGradients) {
  56504. this._lifeTimeGradients = [];
  56505. }
  56506. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56507. return this;
  56508. };
  56509. /**
  56510. * Remove a specific life time gradient
  56511. * @param gradient defines the gradient to remove
  56512. * @returns the current particle system
  56513. */
  56514. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56515. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56516. return this;
  56517. };
  56518. /**
  56519. * Adds a new size gradient
  56520. * @param gradient defines the gradient to use (between 0 and 1)
  56521. * @param factor defines the size factor to affect to the specified gradient
  56522. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56523. * @returns the current particle system
  56524. */
  56525. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56526. if (!this._sizeGradients) {
  56527. this._sizeGradients = [];
  56528. }
  56529. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56530. return this;
  56531. };
  56532. /**
  56533. * Remove a specific size gradient
  56534. * @param gradient defines the gradient to remove
  56535. * @returns the current particle system
  56536. */
  56537. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56538. this._removeFactorGradient(this._sizeGradients, gradient);
  56539. return this;
  56540. };
  56541. /**
  56542. * Adds a new angular speed gradient
  56543. * @param gradient defines the gradient to use (between 0 and 1)
  56544. * @param factor defines the angular speed to affect to the specified gradient
  56545. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56546. * @returns the current particle system
  56547. */
  56548. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56549. if (!this._angularSpeedGradients) {
  56550. this._angularSpeedGradients = [];
  56551. }
  56552. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56553. return this;
  56554. };
  56555. /**
  56556. * Remove a specific angular speed gradient
  56557. * @param gradient defines the gradient to remove
  56558. * @returns the current particle system
  56559. */
  56560. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56561. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56562. return this;
  56563. };
  56564. /**
  56565. * Adds a new velocity gradient
  56566. * @param gradient defines the gradient to use (between 0 and 1)
  56567. * @param factor defines the velocity to affect to the specified gradient
  56568. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56569. * @returns the current particle system
  56570. */
  56571. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56572. if (!this._velocityGradients) {
  56573. this._velocityGradients = [];
  56574. }
  56575. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56576. return this;
  56577. };
  56578. /**
  56579. * Remove a specific velocity gradient
  56580. * @param gradient defines the gradient to remove
  56581. * @returns the current particle system
  56582. */
  56583. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56584. this._removeFactorGradient(this._velocityGradients, gradient);
  56585. return this;
  56586. };
  56587. /**
  56588. * Adds a new limit velocity gradient
  56589. * @param gradient defines the gradient to use (between 0 and 1)
  56590. * @param factor defines the limit velocity value to affect to the specified gradient
  56591. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56592. * @returns the current particle system
  56593. */
  56594. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56595. if (!this._limitVelocityGradients) {
  56596. this._limitVelocityGradients = [];
  56597. }
  56598. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56599. return this;
  56600. };
  56601. /**
  56602. * Remove a specific limit velocity gradient
  56603. * @param gradient defines the gradient to remove
  56604. * @returns the current particle system
  56605. */
  56606. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56607. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56608. return this;
  56609. };
  56610. /**
  56611. * Adds a new drag gradient
  56612. * @param gradient defines the gradient to use (between 0 and 1)
  56613. * @param factor defines the drag value to affect to the specified gradient
  56614. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56615. * @returns the current particle system
  56616. */
  56617. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56618. if (!this._dragGradients) {
  56619. this._dragGradients = [];
  56620. }
  56621. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56622. return this;
  56623. };
  56624. /**
  56625. * Remove a specific drag gradient
  56626. * @param gradient defines the gradient to remove
  56627. * @returns the current particle system
  56628. */
  56629. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56630. this._removeFactorGradient(this._dragGradients, gradient);
  56631. return this;
  56632. };
  56633. /**
  56634. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56635. * @param gradient defines the gradient to use (between 0 and 1)
  56636. * @param factor defines the emit rate value to affect to the specified gradient
  56637. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56638. * @returns the current particle system
  56639. */
  56640. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56641. if (!this._emitRateGradients) {
  56642. this._emitRateGradients = [];
  56643. }
  56644. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56645. if (!this._currentEmitRateGradient) {
  56646. this._currentEmitRateGradient = this._emitRateGradients[0];
  56647. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56648. this._currentEmitRate2 = this._currentEmitRate1;
  56649. }
  56650. if (this._emitRateGradients.length === 2) {
  56651. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56652. }
  56653. return this;
  56654. };
  56655. /**
  56656. * Remove a specific emit rate gradient
  56657. * @param gradient defines the gradient to remove
  56658. * @returns the current particle system
  56659. */
  56660. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56661. this._removeFactorGradient(this._emitRateGradients, gradient);
  56662. return this;
  56663. };
  56664. /**
  56665. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56666. * @param gradient defines the gradient to use (between 0 and 1)
  56667. * @param factor defines the start size value to affect to the specified gradient
  56668. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56669. * @returns the current particle system
  56670. */
  56671. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56672. if (!this._startSizeGradients) {
  56673. this._startSizeGradients = [];
  56674. }
  56675. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56676. if (!this._currentStartSizeGradient) {
  56677. this._currentStartSizeGradient = this._startSizeGradients[0];
  56678. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56679. this._currentStartSize2 = this._currentStartSize1;
  56680. }
  56681. if (this._startSizeGradients.length === 2) {
  56682. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56683. }
  56684. return this;
  56685. };
  56686. /**
  56687. * Remove a specific start size gradient
  56688. * @param gradient defines the gradient to remove
  56689. * @returns the current particle system
  56690. */
  56691. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56692. this._removeFactorGradient(this._emitRateGradients, gradient);
  56693. return this;
  56694. };
  56695. /**
  56696. * Adds a new color gradient
  56697. * @param gradient defines the gradient to use (between 0 and 1)
  56698. * @param color defines the color to affect to the specified gradient
  56699. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56700. */
  56701. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56702. if (!this._colorGradients) {
  56703. this._colorGradients = [];
  56704. }
  56705. var colorGradient = new BABYLON.ColorGradient();
  56706. colorGradient.gradient = gradient;
  56707. colorGradient.color1 = color;
  56708. colorGradient.color2 = color2;
  56709. this._colorGradients.push(colorGradient);
  56710. this._colorGradients.sort(function (a, b) {
  56711. if (a.gradient < b.gradient) {
  56712. return -1;
  56713. }
  56714. else if (a.gradient > b.gradient) {
  56715. return 1;
  56716. }
  56717. return 0;
  56718. });
  56719. return this;
  56720. };
  56721. /**
  56722. * Remove a specific color gradient
  56723. * @param gradient defines the gradient to remove
  56724. */
  56725. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56726. if (!this._colorGradients) {
  56727. return this;
  56728. }
  56729. var index = 0;
  56730. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56731. var colorGradient = _a[_i];
  56732. if (colorGradient.gradient === gradient) {
  56733. this._colorGradients.splice(index, 1);
  56734. break;
  56735. }
  56736. index++;
  56737. }
  56738. return this;
  56739. };
  56740. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56741. u = Math.abs(u) * 0.5 + 0.5;
  56742. v = Math.abs(v) * 0.5 + 0.5;
  56743. var wrappedU = ((u * width) % width) | 0;
  56744. var wrappedV = ((v * height) % height) | 0;
  56745. var position = (wrappedU + wrappedV * width) * 4;
  56746. return pixels[position] / 255;
  56747. };
  56748. ParticleSystem.prototype._reset = function () {
  56749. this._resetEffect();
  56750. };
  56751. ParticleSystem.prototype._resetEffect = function () {
  56752. if (this._vertexBuffer) {
  56753. this._vertexBuffer.dispose();
  56754. this._vertexBuffer = null;
  56755. }
  56756. if (this._spriteBuffer) {
  56757. this._spriteBuffer.dispose();
  56758. this._spriteBuffer = null;
  56759. }
  56760. this._createVertexBuffers();
  56761. };
  56762. ParticleSystem.prototype._createVertexBuffers = function () {
  56763. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56764. if (this._isAnimationSheetEnabled) {
  56765. this._vertexBufferSize += 1;
  56766. }
  56767. if (!this._isBillboardBased) {
  56768. this._vertexBufferSize += 3;
  56769. }
  56770. var engine = this._scene.getEngine();
  56771. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56772. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56773. var dataOffset = 0;
  56774. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56775. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56776. dataOffset += 3;
  56777. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56778. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56779. dataOffset += 4;
  56780. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56781. this._vertexBuffers["angle"] = options;
  56782. dataOffset += 1;
  56783. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56784. this._vertexBuffers["size"] = size;
  56785. dataOffset += 2;
  56786. if (this._isAnimationSheetEnabled) {
  56787. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56788. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56789. dataOffset += 1;
  56790. }
  56791. if (!this._isBillboardBased) {
  56792. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56793. this._vertexBuffers["direction"] = directionBuffer;
  56794. dataOffset += 3;
  56795. }
  56796. var offsets;
  56797. if (this._useInstancing) {
  56798. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56799. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56800. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56801. }
  56802. else {
  56803. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56804. dataOffset += 2;
  56805. }
  56806. this._vertexBuffers["offset"] = offsets;
  56807. };
  56808. ParticleSystem.prototype._createIndexBuffer = function () {
  56809. if (this._useInstancing) {
  56810. return;
  56811. }
  56812. var indices = [];
  56813. var index = 0;
  56814. for (var count = 0; count < this._capacity; count++) {
  56815. indices.push(index);
  56816. indices.push(index + 1);
  56817. indices.push(index + 2);
  56818. indices.push(index);
  56819. indices.push(index + 2);
  56820. indices.push(index + 3);
  56821. index += 4;
  56822. }
  56823. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56824. };
  56825. /**
  56826. * Gets the maximum number of particles active at the same time.
  56827. * @returns The max number of active particles.
  56828. */
  56829. ParticleSystem.prototype.getCapacity = function () {
  56830. return this._capacity;
  56831. };
  56832. /**
  56833. * Gets whether there are still active particles in the system.
  56834. * @returns True if it is alive, otherwise false.
  56835. */
  56836. ParticleSystem.prototype.isAlive = function () {
  56837. return this._alive;
  56838. };
  56839. /**
  56840. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56841. * @returns True if it has been started, otherwise false.
  56842. */
  56843. ParticleSystem.prototype.isStarted = function () {
  56844. return this._started;
  56845. };
  56846. /**
  56847. * Starts the particle system and begins to emit
  56848. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56849. */
  56850. ParticleSystem.prototype.start = function (delay) {
  56851. var _this = this;
  56852. if (delay === void 0) { delay = 0; }
  56853. if (delay) {
  56854. setTimeout(function () {
  56855. _this.start(0);
  56856. }, delay);
  56857. return;
  56858. }
  56859. this._started = true;
  56860. this._stopped = false;
  56861. this._actualFrame = 0;
  56862. if (this.subEmitters && this.subEmitters.length != 0) {
  56863. this.activeSubSystems = new Array();
  56864. }
  56865. if (this.preWarmCycles) {
  56866. for (var index = 0; index < this.preWarmCycles; index++) {
  56867. this.animate(true);
  56868. }
  56869. }
  56870. };
  56871. /**
  56872. * Stops the particle system.
  56873. * @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.
  56874. */
  56875. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56876. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56877. this._stopped = true;
  56878. if (stopSubEmitters) {
  56879. this._stopSubEmitters();
  56880. }
  56881. };
  56882. // animation sheet
  56883. /**
  56884. * Remove all active particles
  56885. */
  56886. ParticleSystem.prototype.reset = function () {
  56887. this._stockParticles = [];
  56888. this._particles = [];
  56889. };
  56890. /**
  56891. * @hidden (for internal use only)
  56892. */
  56893. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56894. var offset = index * this._vertexBufferSize;
  56895. this._vertexData[offset++] = particle.position.x;
  56896. this._vertexData[offset++] = particle.position.y;
  56897. this._vertexData[offset++] = particle.position.z;
  56898. this._vertexData[offset++] = particle.color.r;
  56899. this._vertexData[offset++] = particle.color.g;
  56900. this._vertexData[offset++] = particle.color.b;
  56901. this._vertexData[offset++] = particle.color.a;
  56902. this._vertexData[offset++] = particle.angle;
  56903. this._vertexData[offset++] = particle.scale.x * particle.size;
  56904. this._vertexData[offset++] = particle.scale.y * particle.size;
  56905. if (this._isAnimationSheetEnabled) {
  56906. this._vertexData[offset++] = particle.cellIndex;
  56907. }
  56908. if (!this._isBillboardBased) {
  56909. if (particle._initialDirection) {
  56910. this._vertexData[offset++] = particle._initialDirection.x;
  56911. this._vertexData[offset++] = particle._initialDirection.y;
  56912. this._vertexData[offset++] = particle._initialDirection.z;
  56913. }
  56914. else {
  56915. this._vertexData[offset++] = particle.direction.x;
  56916. this._vertexData[offset++] = particle.direction.y;
  56917. this._vertexData[offset++] = particle.direction.z;
  56918. }
  56919. }
  56920. if (!this._useInstancing) {
  56921. if (this._isAnimationSheetEnabled) {
  56922. if (offsetX === 0)
  56923. offsetX = this._epsilon;
  56924. else if (offsetX === 1)
  56925. offsetX = 1 - this._epsilon;
  56926. if (offsetY === 0)
  56927. offsetY = this._epsilon;
  56928. else if (offsetY === 1)
  56929. offsetY = 1 - this._epsilon;
  56930. }
  56931. this._vertexData[offset++] = offsetX;
  56932. this._vertexData[offset++] = offsetY;
  56933. }
  56934. };
  56935. ParticleSystem.prototype._stopSubEmitters = function () {
  56936. if (!this.activeSubSystems) {
  56937. return;
  56938. }
  56939. this.activeSubSystems.forEach(function (subSystem) {
  56940. subSystem.stop(true);
  56941. });
  56942. this.activeSubSystems = new Array();
  56943. };
  56944. ParticleSystem.prototype._removeFromRoot = function () {
  56945. if (!this._rootParticleSystem) {
  56946. return;
  56947. }
  56948. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56949. if (index !== -1) {
  56950. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56951. }
  56952. };
  56953. // End of sub system methods
  56954. ParticleSystem.prototype._update = function (newParticles) {
  56955. var _this = this;
  56956. // Update current
  56957. this._alive = this._particles.length > 0;
  56958. if (this.emitter.position) {
  56959. var emitterMesh = this.emitter;
  56960. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56961. }
  56962. else {
  56963. var emitterPosition = this.emitter;
  56964. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56965. }
  56966. this.updateFunction(this._particles);
  56967. // Add new ones
  56968. var particle;
  56969. var _loop_2 = function () {
  56970. if (this_1._particles.length === this_1._capacity) {
  56971. return "break";
  56972. }
  56973. particle = this_1._createParticle();
  56974. this_1._particles.push(particle);
  56975. // Emitter
  56976. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56977. if (this_1.startPositionFunction) {
  56978. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56979. }
  56980. else {
  56981. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56982. }
  56983. if (this_1.startDirectionFunction) {
  56984. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56985. }
  56986. else {
  56987. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56988. }
  56989. if (emitPower === 0) {
  56990. if (!particle._initialDirection) {
  56991. particle._initialDirection = particle.direction.clone();
  56992. }
  56993. else {
  56994. particle._initialDirection.copyFrom(particle.direction);
  56995. }
  56996. }
  56997. else {
  56998. particle._initialDirection = null;
  56999. }
  57000. particle.direction.scaleInPlace(emitPower);
  57001. // Life time
  57002. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57003. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57004. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57005. var factorGradient1 = currentGradient;
  57006. var factorGradient2 = nextGradient;
  57007. var lifeTime1 = factorGradient1.getFactor();
  57008. var lifeTime2 = factorGradient2.getFactor();
  57009. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57010. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57011. });
  57012. }
  57013. else {
  57014. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57015. }
  57016. // Size
  57017. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57018. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57019. }
  57020. else {
  57021. particle._currentSizeGradient = this_1._sizeGradients[0];
  57022. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57023. particle.size = particle._currentSize1;
  57024. if (this_1._sizeGradients.length > 1) {
  57025. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57026. }
  57027. else {
  57028. particle._currentSize2 = particle._currentSize1;
  57029. }
  57030. }
  57031. // Size and scale
  57032. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57033. // Adjust scale by start size
  57034. if (this_1._startSizeGradients && this_1._startSizeGradients[0]) {
  57035. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57036. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57037. if (currentGradient !== _this._currentStartSizeGradient) {
  57038. _this._currentStartSize1 = _this._currentStartSize2;
  57039. _this._currentStartSize2 = nextGradient.getFactor();
  57040. _this._currentStartSizeGradient = currentGradient;
  57041. }
  57042. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57043. particle.scale.scaleInPlace(value);
  57044. });
  57045. }
  57046. // Angle
  57047. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57048. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57049. }
  57050. else {
  57051. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57052. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57053. particle._currentAngularSpeed1 = particle.angularSpeed;
  57054. if (this_1._angularSpeedGradients.length > 1) {
  57055. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57056. }
  57057. else {
  57058. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57059. }
  57060. }
  57061. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57062. // Velocity
  57063. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57064. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57065. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57066. if (this_1._velocityGradients.length > 1) {
  57067. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57068. }
  57069. else {
  57070. particle._currentVelocity2 = particle._currentVelocity1;
  57071. }
  57072. }
  57073. // Limit velocity
  57074. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57075. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57076. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57077. if (this_1._limitVelocityGradients.length > 1) {
  57078. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57079. }
  57080. else {
  57081. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57082. }
  57083. }
  57084. // Drag
  57085. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57086. particle._currentDragGradient = this_1._dragGradients[0];
  57087. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57088. if (this_1._dragGradients.length > 1) {
  57089. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57090. }
  57091. else {
  57092. particle._currentDrag2 = particle._currentDrag1;
  57093. }
  57094. }
  57095. // Color
  57096. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57097. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57098. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57099. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57100. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57101. }
  57102. else {
  57103. particle._currentColorGradient = this_1._colorGradients[0];
  57104. particle._currentColorGradient.getColorToRef(particle.color);
  57105. particle._currentColor1.copyFrom(particle.color);
  57106. if (this_1._colorGradients.length > 1) {
  57107. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57108. }
  57109. else {
  57110. particle._currentColor2.copyFrom(particle.color);
  57111. }
  57112. }
  57113. // Sheet
  57114. if (this_1._isAnimationSheetEnabled) {
  57115. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57116. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57117. }
  57118. };
  57119. var this_1 = this, step;
  57120. for (var index = 0; index < newParticles; index++) {
  57121. var state_1 = _loop_2();
  57122. if (state_1 === "break")
  57123. break;
  57124. }
  57125. };
  57126. /** @hidden */
  57127. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  57128. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57129. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57130. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57131. if (isAnimationSheetEnabled) {
  57132. attributeNamesOrOptions.push("cellIndex");
  57133. }
  57134. if (!isBillboardBased) {
  57135. attributeNamesOrOptions.push("direction");
  57136. }
  57137. return attributeNamesOrOptions;
  57138. };
  57139. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57140. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57141. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57142. if (isAnimationSheetEnabled) {
  57143. effectCreationOption.push("particlesInfos");
  57144. }
  57145. return effectCreationOption;
  57146. };
  57147. ParticleSystem.prototype._getEffect = function () {
  57148. if (this._customEffect) {
  57149. return this._customEffect;
  57150. }
  57151. ;
  57152. var defines = [];
  57153. if (this._scene.clipPlane) {
  57154. defines.push("#define CLIPPLANE");
  57155. }
  57156. if (this._scene.clipPlane2) {
  57157. defines.push("#define CLIPPLANE2");
  57158. }
  57159. if (this._scene.clipPlane3) {
  57160. defines.push("#define CLIPPLANE3");
  57161. }
  57162. if (this._scene.clipPlane4) {
  57163. defines.push("#define CLIPPLANE4");
  57164. }
  57165. if (this._isAnimationSheetEnabled) {
  57166. defines.push("#define ANIMATESHEET");
  57167. }
  57168. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57169. defines.push("#define BLENDMULTIPLYMODE");
  57170. }
  57171. if (this._isBillboardBased) {
  57172. defines.push("#define BILLBOARD");
  57173. switch (this.billboardMode) {
  57174. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57175. defines.push("#define BILLBOARDY");
  57176. break;
  57177. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57178. default:
  57179. break;
  57180. }
  57181. }
  57182. if (this._imageProcessingConfiguration) {
  57183. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57184. defines.push(this._imageProcessingConfigurationDefines.toString());
  57185. }
  57186. // Effect
  57187. var join = defines.join("\n");
  57188. if (this._cachedDefines !== join) {
  57189. this._cachedDefines = join;
  57190. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  57191. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57192. var samplers = ["diffuseSampler"];
  57193. if (BABYLON.ImageProcessingConfiguration) {
  57194. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57195. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57196. }
  57197. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  57198. }
  57199. return this._effect;
  57200. };
  57201. /**
  57202. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57203. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57204. */
  57205. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57206. var _this = this;
  57207. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57208. if (!this._started)
  57209. return;
  57210. if (!preWarmOnly) {
  57211. var effect = this._getEffect();
  57212. // Check
  57213. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57214. return;
  57215. if (this._currentRenderId === this._scene.getRenderId()) {
  57216. return;
  57217. }
  57218. this._currentRenderId = this._scene.getRenderId();
  57219. }
  57220. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57221. // Determine the number of particles we need to create
  57222. var newParticles;
  57223. if (this.manualEmitCount > -1) {
  57224. newParticles = this.manualEmitCount;
  57225. this._newPartsExcess = 0;
  57226. this.manualEmitCount = 0;
  57227. }
  57228. else {
  57229. var rate_1 = this.emitRate;
  57230. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57231. var ratio = this._actualFrame / this.targetStopDuration;
  57232. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57233. if (currentGradient !== _this._currentEmitRateGradient) {
  57234. _this._currentEmitRate1 = _this._currentEmitRate2;
  57235. _this._currentEmitRate2 = nextGradient.getFactor();
  57236. _this._currentEmitRateGradient = currentGradient;
  57237. }
  57238. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57239. });
  57240. }
  57241. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57242. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57243. }
  57244. if (this._newPartsExcess > 1.0) {
  57245. newParticles += this._newPartsExcess >> 0;
  57246. this._newPartsExcess -= this._newPartsExcess >> 0;
  57247. }
  57248. this._alive = false;
  57249. if (!this._stopped) {
  57250. this._actualFrame += this._scaledUpdateSpeed;
  57251. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57252. this.stop();
  57253. }
  57254. else {
  57255. newParticles = 0;
  57256. }
  57257. this._update(newParticles);
  57258. // Stopped?
  57259. if (this._stopped) {
  57260. if (!this._alive) {
  57261. this._started = false;
  57262. if (this.onAnimationEnd) {
  57263. this.onAnimationEnd();
  57264. }
  57265. if (this.disposeOnStop) {
  57266. this._scene._toBeDisposed.push(this);
  57267. }
  57268. }
  57269. }
  57270. if (!preWarmOnly) {
  57271. // Update VBO
  57272. var offset = 0;
  57273. for (var index = 0; index < this._particles.length; index++) {
  57274. var particle = this._particles[index];
  57275. this._appendParticleVertices(offset, particle);
  57276. offset += this._useInstancing ? 1 : 4;
  57277. }
  57278. if (this._vertexBuffer) {
  57279. this._vertexBuffer.update(this._vertexData);
  57280. }
  57281. }
  57282. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57283. this.stop();
  57284. }
  57285. };
  57286. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57287. this._appendParticleVertex(offset++, particle, 0, 0);
  57288. if (!this._useInstancing) {
  57289. this._appendParticleVertex(offset++, particle, 1, 0);
  57290. this._appendParticleVertex(offset++, particle, 1, 1);
  57291. this._appendParticleVertex(offset++, particle, 0, 1);
  57292. }
  57293. };
  57294. /**
  57295. * Rebuilds the particle system.
  57296. */
  57297. ParticleSystem.prototype.rebuild = function () {
  57298. this._createIndexBuffer();
  57299. if (this._vertexBuffer) {
  57300. this._vertexBuffer._rebuild();
  57301. }
  57302. };
  57303. /**
  57304. * Is this system ready to be used/rendered
  57305. * @return true if the system is ready
  57306. */
  57307. ParticleSystem.prototype.isReady = function () {
  57308. var effect = this._getEffect();
  57309. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57310. return false;
  57311. }
  57312. return true;
  57313. };
  57314. /**
  57315. * Renders the particle system in its current state.
  57316. * @returns the current number of particles
  57317. */
  57318. ParticleSystem.prototype.render = function () {
  57319. var effect = this._getEffect();
  57320. // Check
  57321. if (!this.isReady() || !this._particles.length) {
  57322. return 0;
  57323. }
  57324. var engine = this._scene.getEngine();
  57325. // Render
  57326. engine.enableEffect(effect);
  57327. engine.setState(false);
  57328. var viewMatrix = this._scene.getViewMatrix();
  57329. effect.setTexture("diffuseSampler", this.particleTexture);
  57330. effect.setMatrix("view", viewMatrix);
  57331. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57332. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57333. var baseSize = this.particleTexture.getBaseSize();
  57334. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57335. }
  57336. effect.setVector2("translationPivot", this.translationPivot);
  57337. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57338. if (this._isBillboardBased) {
  57339. var camera = this._scene.activeCamera;
  57340. effect.setVector3("eyePosition", camera.globalPosition);
  57341. }
  57342. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57343. var invView = viewMatrix.clone();
  57344. invView.invert();
  57345. effect.setMatrix("invView", invView);
  57346. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57347. }
  57348. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57349. // image processing
  57350. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57351. this._imageProcessingConfiguration.bind(effect);
  57352. }
  57353. // Draw order
  57354. switch (this.blendMode) {
  57355. case ParticleSystem.BLENDMODE_ADD:
  57356. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57357. break;
  57358. case ParticleSystem.BLENDMODE_ONEONE:
  57359. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57360. break;
  57361. case ParticleSystem.BLENDMODE_STANDARD:
  57362. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57363. break;
  57364. case ParticleSystem.BLENDMODE_MULTIPLY:
  57365. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57366. break;
  57367. }
  57368. if (this.forceDepthWrite) {
  57369. engine.setDepthWrite(true);
  57370. }
  57371. if (this._useInstancing) {
  57372. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57373. engine.unbindInstanceAttributes();
  57374. }
  57375. else {
  57376. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57377. }
  57378. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57379. return this._particles.length;
  57380. };
  57381. /**
  57382. * Disposes the particle system and free the associated resources
  57383. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57384. */
  57385. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57386. if (disposeTexture === void 0) { disposeTexture = true; }
  57387. if (this._vertexBuffer) {
  57388. this._vertexBuffer.dispose();
  57389. this._vertexBuffer = null;
  57390. }
  57391. if (this._spriteBuffer) {
  57392. this._spriteBuffer.dispose();
  57393. this._spriteBuffer = null;
  57394. }
  57395. if (this._indexBuffer) {
  57396. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57397. this._indexBuffer = null;
  57398. }
  57399. if (disposeTexture && this.particleTexture) {
  57400. this.particleTexture.dispose();
  57401. this.particleTexture = null;
  57402. }
  57403. if (disposeTexture && this.noiseTexture) {
  57404. this.noiseTexture.dispose();
  57405. this.noiseTexture = null;
  57406. }
  57407. this._removeFromRoot();
  57408. // Remove from scene
  57409. var index = this._scene.particleSystems.indexOf(this);
  57410. if (index > -1) {
  57411. this._scene.particleSystems.splice(index, 1);
  57412. }
  57413. // Callback
  57414. this.onDisposeObservable.notifyObservers(this);
  57415. this.onDisposeObservable.clear();
  57416. };
  57417. // Clone
  57418. /**
  57419. * Clones the particle system.
  57420. * @param name The name of the cloned object
  57421. * @param newEmitter The new emitter to use
  57422. * @returns the cloned particle system
  57423. */
  57424. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57425. var custom = null;
  57426. var program = null;
  57427. if (this.customShader != null) {
  57428. program = this.customShader;
  57429. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57430. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57431. }
  57432. else if (this._customEffect) {
  57433. custom = this._customEffect;
  57434. }
  57435. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57436. result.customShader = program;
  57437. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57438. if (newEmitter === undefined) {
  57439. newEmitter = this.emitter;
  57440. }
  57441. result.emitter = newEmitter;
  57442. if (this.particleTexture) {
  57443. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57444. }
  57445. if (!this.preventAutoStart) {
  57446. result.start();
  57447. }
  57448. return result;
  57449. };
  57450. /**
  57451. * Serializes the particle system to a JSON object.
  57452. * @returns the JSON object
  57453. */
  57454. ParticleSystem.prototype.serialize = function () {
  57455. var serializationObject = {};
  57456. ParticleSystem._Serialize(serializationObject, this);
  57457. serializationObject.textureMask = this.textureMask.asArray();
  57458. serializationObject.customShader = this.customShader;
  57459. serializationObject.preventAutoStart = this.preventAutoStart;
  57460. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57461. return serializationObject;
  57462. };
  57463. /** @hidden */
  57464. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57465. serializationObject.name = particleSystem.name;
  57466. serializationObject.id = particleSystem.id;
  57467. serializationObject.capacity = particleSystem.getCapacity();
  57468. // Emitter
  57469. if (particleSystem.emitter.position) {
  57470. var emitterMesh = particleSystem.emitter;
  57471. serializationObject.emitterId = emitterMesh.id;
  57472. }
  57473. else {
  57474. var emitterPosition = particleSystem.emitter;
  57475. serializationObject.emitter = emitterPosition.asArray();
  57476. }
  57477. // Emitter
  57478. if (particleSystem.particleEmitterType) {
  57479. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57480. }
  57481. if (particleSystem.particleTexture) {
  57482. serializationObject.textureName = particleSystem.particleTexture.name;
  57483. }
  57484. // Animations
  57485. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57486. // Particle system
  57487. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57488. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57489. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57490. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57491. serializationObject.minSize = particleSystem.minSize;
  57492. serializationObject.maxSize = particleSystem.maxSize;
  57493. serializationObject.minScaleX = particleSystem.minScaleX;
  57494. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57495. serializationObject.minScaleY = particleSystem.minScaleY;
  57496. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57497. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57498. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57499. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57500. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57501. serializationObject.emitRate = particleSystem.emitRate;
  57502. serializationObject.gravity = particleSystem.gravity.asArray();
  57503. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57504. serializationObject.color1 = particleSystem.color1.asArray();
  57505. serializationObject.color2 = particleSystem.color2.asArray();
  57506. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57507. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57508. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57509. serializationObject.blendMode = particleSystem.blendMode;
  57510. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57511. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57512. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57513. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57514. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57515. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57516. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57517. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57518. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57519. var colorGradients = particleSystem.getColorGradients();
  57520. if (colorGradients) {
  57521. serializationObject.colorGradients = [];
  57522. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57523. var colorGradient = colorGradients_1[_i];
  57524. var serializedGradient = {
  57525. gradient: colorGradient.gradient,
  57526. color1: colorGradient.color1.asArray()
  57527. };
  57528. if (colorGradient.color2) {
  57529. serializedGradient.color2 = colorGradient.color2.asArray();
  57530. }
  57531. serializationObject.colorGradients.push(serializedGradient);
  57532. }
  57533. }
  57534. var sizeGradients = particleSystem.getSizeGradients();
  57535. if (sizeGradients) {
  57536. serializationObject.sizeGradients = [];
  57537. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57538. var sizeGradient = sizeGradients_1[_a];
  57539. var serializedGradient = {
  57540. gradient: sizeGradient.gradient,
  57541. factor1: sizeGradient.factor1
  57542. };
  57543. if (sizeGradient.factor2 !== undefined) {
  57544. serializedGradient.factor2 = sizeGradient.factor2;
  57545. }
  57546. serializationObject.sizeGradients.push(serializedGradient);
  57547. }
  57548. }
  57549. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57550. if (angularSpeedGradients) {
  57551. serializationObject.angularSpeedGradients = [];
  57552. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57553. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57554. var serializedGradient = {
  57555. gradient: angularSpeedGradient.gradient,
  57556. factor1: angularSpeedGradient.factor1
  57557. };
  57558. if (angularSpeedGradient.factor2 !== undefined) {
  57559. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57560. }
  57561. serializationObject.angularSpeedGradients.push(serializedGradient);
  57562. }
  57563. }
  57564. var velocityGradients = particleSystem.getVelocityGradients();
  57565. if (velocityGradients) {
  57566. serializationObject.velocityGradients = [];
  57567. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57568. var velocityGradient = velocityGradients_1[_c];
  57569. var serializedGradient = {
  57570. gradient: velocityGradient.gradient,
  57571. factor1: velocityGradient.factor1
  57572. };
  57573. if (velocityGradient.factor2 !== undefined) {
  57574. serializedGradient.factor2 = velocityGradient.factor2;
  57575. }
  57576. serializationObject.velocityGradients.push(serializedGradient);
  57577. }
  57578. }
  57579. var dragGradients = particleSystem.getDragGradients();
  57580. if (dragGradients) {
  57581. serializationObject.dragyGradients = [];
  57582. for (var _d = 0, dragGradients_1 = dragGradients; _d < dragGradients_1.length; _d++) {
  57583. var dragGradient = dragGradients_1[_d];
  57584. var serializedGradient = {
  57585. gradient: dragGradient.gradient,
  57586. factor1: dragGradient.factor1
  57587. };
  57588. if (dragGradient.factor2 !== undefined) {
  57589. serializedGradient.factor2 = dragGradient.factor2;
  57590. }
  57591. serializationObject.dragGradients.push(serializedGradient);
  57592. }
  57593. }
  57594. var emitRateGradients = particleSystem.getEmitRateGradients();
  57595. if (emitRateGradients) {
  57596. serializationObject.emitRateGradients = [];
  57597. for (var _e = 0, emitRateGradients_1 = emitRateGradients; _e < emitRateGradients_1.length; _e++) {
  57598. var emitRateGradient = emitRateGradients_1[_e];
  57599. var serializedGradient = {
  57600. gradient: emitRateGradient.gradient,
  57601. factor1: emitRateGradient.factor1
  57602. };
  57603. if (emitRateGradient.factor2 !== undefined) {
  57604. serializedGradient.factor2 = emitRateGradient.factor2;
  57605. }
  57606. serializationObject.emitRateGradients.push(serializedGradient);
  57607. }
  57608. }
  57609. var startSizeGradients = particleSystem.getStartSizeGradients();
  57610. if (startSizeGradients) {
  57611. serializationObject.startSizeGradients = [];
  57612. for (var _f = 0, startSizeGradients_1 = startSizeGradients; _f < startSizeGradients_1.length; _f++) {
  57613. var startSizeGradient = startSizeGradients_1[_f];
  57614. var serializedGradient = {
  57615. gradient: startSizeGradient.gradient,
  57616. factor1: startSizeGradient.factor1
  57617. };
  57618. if (startSizeGradient.factor2 !== undefined) {
  57619. serializedGradient.factor2 = startSizeGradient.factor2;
  57620. }
  57621. serializationObject.startSizeGradients.push(serializedGradient);
  57622. }
  57623. }
  57624. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57625. if (limitVelocityGradients) {
  57626. serializationObject.limitVelocityGradients = [];
  57627. for (var _g = 0, limitVelocityGradients_1 = limitVelocityGradients; _g < limitVelocityGradients_1.length; _g++) {
  57628. var limitVelocityGradient = limitVelocityGradients_1[_g];
  57629. var serializedGradient = {
  57630. gradient: limitVelocityGradient.gradient,
  57631. factor1: limitVelocityGradient.factor1
  57632. };
  57633. if (limitVelocityGradient.factor2 !== undefined) {
  57634. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57635. }
  57636. serializationObject.limitVelocityGradients.push(serializedGradient);
  57637. }
  57638. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57639. }
  57640. if (BABYLON.ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57641. var noiseTexture = particleSystem.noiseTexture;
  57642. serializationObject.noiseTexture = noiseTexture.serialize();
  57643. }
  57644. };
  57645. /** @hidden */
  57646. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57647. // Texture
  57648. if (parsedParticleSystem.textureName) {
  57649. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57650. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57651. }
  57652. // Emitter
  57653. if (parsedParticleSystem.emitterId === undefined) {
  57654. particleSystem.emitter = BABYLON.Vector3.Zero();
  57655. }
  57656. else if (parsedParticleSystem.emitterId) {
  57657. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57658. }
  57659. else {
  57660. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57661. }
  57662. // Misc.
  57663. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57664. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57665. }
  57666. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57667. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57668. }
  57669. // Animations
  57670. if (parsedParticleSystem.animations) {
  57671. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57672. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57673. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57674. }
  57675. }
  57676. if (parsedParticleSystem.autoAnimate) {
  57677. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57678. }
  57679. // Particle system
  57680. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57681. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57682. particleSystem.minSize = parsedParticleSystem.minSize;
  57683. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57684. if (parsedParticleSystem.minScaleX) {
  57685. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57686. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57687. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57688. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57689. }
  57690. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57691. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57692. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57693. }
  57694. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57695. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57696. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57697. }
  57698. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57699. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57700. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57701. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57702. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57703. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57704. if (parsedParticleSystem.noiseStrength) {
  57705. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57706. }
  57707. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57708. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57709. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57710. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57711. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57712. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57713. if (parsedParticleSystem.colorGradients) {
  57714. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57715. var colorGradient = _a[_i];
  57716. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57717. }
  57718. }
  57719. if (parsedParticleSystem.sizeGradients) {
  57720. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57721. var sizeGradient = _c[_b];
  57722. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57723. }
  57724. }
  57725. if (parsedParticleSystem.angularSpeedGradients) {
  57726. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57727. var angularSpeedGradient = _e[_d];
  57728. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57729. }
  57730. }
  57731. if (parsedParticleSystem.velocityGradients) {
  57732. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57733. var velocityGradient = _g[_f];
  57734. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57735. }
  57736. }
  57737. if (parsedParticleSystem.dragGradients) {
  57738. for (var _h = 0, _j = parsedParticleSystem.dragGradients; _h < _j.length; _h++) {
  57739. var dragGradient = _j[_h];
  57740. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57741. }
  57742. }
  57743. if (parsedParticleSystem.emitRateGradients) {
  57744. for (var _k = 0, _l = parsedParticleSystem.emitRateGradients; _k < _l.length; _k++) {
  57745. var emitRateGradient = _l[_k];
  57746. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57747. }
  57748. }
  57749. if (parsedParticleSystem.startSizeGradients) {
  57750. for (var _m = 0, _o = parsedParticleSystem.startSizeGradients; _m < _o.length; _m++) {
  57751. var startSizeGradient = _o[_m];
  57752. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  57753. }
  57754. }
  57755. if (parsedParticleSystem.limitVelocityGradients) {
  57756. for (var _p = 0, _q = parsedParticleSystem.limitVelocityGradients; _p < _q.length; _p++) {
  57757. var limitVelocityGradient = _q[_p];
  57758. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57759. }
  57760. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57761. }
  57762. if (parsedParticleSystem.noiseTexture) {
  57763. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57764. }
  57765. // Emitter
  57766. var emitterType;
  57767. if (parsedParticleSystem.particleEmitterType) {
  57768. switch (parsedParticleSystem.particleEmitterType.type) {
  57769. case "SphereParticleEmitter":
  57770. emitterType = new BABYLON.SphereParticleEmitter();
  57771. break;
  57772. case "SphereDirectedParticleEmitter":
  57773. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57774. break;
  57775. case "ConeEmitter":
  57776. case "ConeParticleEmitter":
  57777. emitterType = new BABYLON.ConeParticleEmitter();
  57778. break;
  57779. case "BoxEmitter":
  57780. case "BoxParticleEmitter":
  57781. default:
  57782. emitterType = new BABYLON.BoxParticleEmitter();
  57783. break;
  57784. }
  57785. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57786. }
  57787. else {
  57788. emitterType = new BABYLON.BoxParticleEmitter();
  57789. emitterType.parse(parsedParticleSystem);
  57790. }
  57791. particleSystem.particleEmitterType = emitterType;
  57792. // Animation sheet
  57793. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57794. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57795. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57796. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57797. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57798. };
  57799. /**
  57800. * Parses a JSON object to create a particle system.
  57801. * @param parsedParticleSystem The JSON object to parse
  57802. * @param scene The scene to create the particle system in
  57803. * @param rootUrl The root url to use to load external dependencies like texture
  57804. * @returns the Parsed particle system
  57805. */
  57806. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57807. var name = parsedParticleSystem.name;
  57808. var custom = null;
  57809. var program = null;
  57810. if (parsedParticleSystem.customShader) {
  57811. program = parsedParticleSystem.customShader;
  57812. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57813. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57814. }
  57815. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57816. particleSystem.customShader = program;
  57817. if (parsedParticleSystem.id) {
  57818. particleSystem.id = parsedParticleSystem.id;
  57819. }
  57820. // Auto start
  57821. if (parsedParticleSystem.preventAutoStart) {
  57822. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57823. }
  57824. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57825. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57826. if (!particleSystem.preventAutoStart) {
  57827. particleSystem.start();
  57828. }
  57829. return particleSystem;
  57830. };
  57831. return ParticleSystem;
  57832. }(BABYLON.BaseParticleSystem));
  57833. BABYLON.ParticleSystem = ParticleSystem;
  57834. })(BABYLON || (BABYLON = {}));
  57835. //# sourceMappingURL=babylon.particleSystem.js.map
  57836. var BABYLON;
  57837. (function (BABYLON) {
  57838. /**
  57839. * Particle emitter emitting particles from the inside of a box.
  57840. * It emits the particles randomly between 2 given directions.
  57841. */
  57842. var BoxParticleEmitter = /** @class */ (function () {
  57843. /**
  57844. * Creates a new instance BoxParticleEmitter
  57845. */
  57846. function BoxParticleEmitter() {
  57847. /**
  57848. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57849. */
  57850. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57851. /**
  57852. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57853. */
  57854. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57855. /**
  57856. * 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.
  57857. */
  57858. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57859. /**
  57860. * 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.
  57861. */
  57862. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57863. }
  57864. /**
  57865. * Called by the particle System when the direction is computed for the created particle.
  57866. * @param worldMatrix is the world matrix of the particle system
  57867. * @param directionToUpdate is the direction vector to update with the result
  57868. * @param particle is the particle we are computed the direction for
  57869. */
  57870. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57871. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57872. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57873. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57874. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57875. };
  57876. /**
  57877. * Called by the particle System when the position is computed for the created particle.
  57878. * @param worldMatrix is the world matrix of the particle system
  57879. * @param positionToUpdate is the position vector to update with the result
  57880. * @param particle is the particle we are computed the position for
  57881. */
  57882. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57883. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57884. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57885. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57886. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57887. };
  57888. /**
  57889. * Clones the current emitter and returns a copy of it
  57890. * @returns the new emitter
  57891. */
  57892. BoxParticleEmitter.prototype.clone = function () {
  57893. var newOne = new BoxParticleEmitter();
  57894. BABYLON.Tools.DeepCopy(this, newOne);
  57895. return newOne;
  57896. };
  57897. /**
  57898. * Called by the GPUParticleSystem to setup the update shader
  57899. * @param effect defines the update shader
  57900. */
  57901. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57902. effect.setVector3("direction1", this.direction1);
  57903. effect.setVector3("direction2", this.direction2);
  57904. effect.setVector3("minEmitBox", this.minEmitBox);
  57905. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57906. };
  57907. /**
  57908. * Returns a string to use to update the GPU particles update shader
  57909. * @returns a string containng the defines string
  57910. */
  57911. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57912. return "#define BOXEMITTER";
  57913. };
  57914. /**
  57915. * Returns the string "BoxParticleEmitter"
  57916. * @returns a string containing the class name
  57917. */
  57918. BoxParticleEmitter.prototype.getClassName = function () {
  57919. return "BoxParticleEmitter";
  57920. };
  57921. /**
  57922. * Serializes the particle system to a JSON object.
  57923. * @returns the JSON object
  57924. */
  57925. BoxParticleEmitter.prototype.serialize = function () {
  57926. var serializationObject = {};
  57927. serializationObject.type = this.getClassName();
  57928. serializationObject.direction1 = this.direction1.asArray();
  57929. serializationObject.direction2 = this.direction2.asArray();
  57930. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57931. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57932. return serializationObject;
  57933. };
  57934. /**
  57935. * Parse properties from a JSON object
  57936. * @param serializationObject defines the JSON object
  57937. */
  57938. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57939. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57940. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57941. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57942. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57943. };
  57944. return BoxParticleEmitter;
  57945. }());
  57946. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57947. })(BABYLON || (BABYLON = {}));
  57948. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57949. var BABYLON;
  57950. (function (BABYLON) {
  57951. /**
  57952. * Particle emitter emitting particles from the inside of a cylinder.
  57953. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57954. */
  57955. var CylinderParticleEmitter = /** @class */ (function () {
  57956. /**
  57957. * Creates a new instance CylinderParticleEmitter
  57958. * @param radius the radius of the emission cylinder (1 by default)
  57959. * @param height the height of the emission cylinder (1 by default)
  57960. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57961. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57962. */
  57963. function CylinderParticleEmitter(
  57964. /**
  57965. * The radius of the emission cylinder.
  57966. */
  57967. radius,
  57968. /**
  57969. * The height of the emission cylinder.
  57970. */
  57971. height,
  57972. /**
  57973. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57974. */
  57975. radiusRange,
  57976. /**
  57977. * How much to randomize the particle direction [0-1].
  57978. */
  57979. directionRandomizer) {
  57980. if (radius === void 0) { radius = 1; }
  57981. if (height === void 0) { height = 1; }
  57982. if (radiusRange === void 0) { radiusRange = 1; }
  57983. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57984. this.radius = radius;
  57985. this.height = height;
  57986. this.radiusRange = radiusRange;
  57987. this.directionRandomizer = directionRandomizer;
  57988. }
  57989. /**
  57990. * Called by the particle System when the direction is computed for the created particle.
  57991. * @param worldMatrix is the world matrix of the particle system
  57992. * @param directionToUpdate is the direction vector to update with the result
  57993. * @param particle is the particle we are computed the direction for
  57994. */
  57995. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57996. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57997. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57998. var angle = Math.atan2(direction.x, direction.z);
  57999. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58000. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58001. direction.x = Math.sin(angle);
  58002. direction.z = Math.cos(angle);
  58003. direction.normalize();
  58004. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58005. };
  58006. /**
  58007. * Called by the particle System when the position is computed for the created particle.
  58008. * @param worldMatrix is the world matrix of the particle system
  58009. * @param positionToUpdate is the position vector to update with the result
  58010. * @param particle is the particle we are computed the position for
  58011. */
  58012. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58013. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58014. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58015. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58016. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58017. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58018. var xPos = positionRadius * Math.cos(angle);
  58019. var zPos = positionRadius * Math.sin(angle);
  58020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58021. };
  58022. /**
  58023. * Clones the current emitter and returns a copy of it
  58024. * @returns the new emitter
  58025. */
  58026. CylinderParticleEmitter.prototype.clone = function () {
  58027. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58028. BABYLON.Tools.DeepCopy(this, newOne);
  58029. return newOne;
  58030. };
  58031. /**
  58032. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58033. * @param effect defines the update shader
  58034. */
  58035. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58036. effect.setFloat("radius", this.radius);
  58037. effect.setFloat("height", this.height);
  58038. effect.setFloat("radiusRange", this.radiusRange);
  58039. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58040. };
  58041. /**
  58042. * Returns a string to use to update the GPU particles update shader
  58043. * @returns a string containng the defines string
  58044. */
  58045. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58046. return "#define CYLINDEREMITTER";
  58047. };
  58048. /**
  58049. * Returns the string "CylinderParticleEmitter"
  58050. * @returns a string containing the class name
  58051. */
  58052. CylinderParticleEmitter.prototype.getClassName = function () {
  58053. return "CylinderParticleEmitter";
  58054. };
  58055. /**
  58056. * Serializes the particle system to a JSON object.
  58057. * @returns the JSON object
  58058. */
  58059. CylinderParticleEmitter.prototype.serialize = function () {
  58060. var serializationObject = {};
  58061. serializationObject.type = this.getClassName();
  58062. serializationObject.radius = this.radius;
  58063. serializationObject.height = this.height;
  58064. serializationObject.radiusRange = this.radiusRange;
  58065. serializationObject.directionRandomizer = this.directionRandomizer;
  58066. return serializationObject;
  58067. };
  58068. /**
  58069. * Parse properties from a JSON object
  58070. * @param serializationObject defines the JSON object
  58071. */
  58072. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58073. this.radius = serializationObject.radius;
  58074. this.height = serializationObject.height;
  58075. this.radiusRange = serializationObject.radiusRange;
  58076. this.directionRandomizer = serializationObject.directionRandomizer;
  58077. };
  58078. return CylinderParticleEmitter;
  58079. }());
  58080. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58081. /**
  58082. * Particle emitter emitting particles from the inside of a cylinder.
  58083. * It emits the particles randomly between two vectors.
  58084. */
  58085. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58086. __extends(CylinderDirectedParticleEmitter, _super);
  58087. /**
  58088. * Creates a new instance CylinderDirectedParticleEmitter
  58089. * @param radius the radius of the emission cylinder (1 by default)
  58090. * @param height the height of the emission cylinder (1 by default)
  58091. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58092. * @param direction1 the min limit of the emission direction (up vector by default)
  58093. * @param direction2 the max limit of the emission direction (up vector by default)
  58094. */
  58095. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58096. /**
  58097. * The min limit of the emission direction.
  58098. */
  58099. direction1,
  58100. /**
  58101. * The max limit of the emission direction.
  58102. */
  58103. direction2) {
  58104. if (radius === void 0) { radius = 1; }
  58105. if (height === void 0) { height = 1; }
  58106. if (radiusRange === void 0) { radiusRange = 1; }
  58107. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58108. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58109. var _this = _super.call(this, radius, height, radiusRange) || this;
  58110. _this.direction1 = direction1;
  58111. _this.direction2 = direction2;
  58112. return _this;
  58113. }
  58114. /**
  58115. * Called by the particle System when the direction is computed for the created particle.
  58116. * @param worldMatrix is the world matrix of the particle system
  58117. * @param directionToUpdate is the direction vector to update with the result
  58118. * @param particle is the particle we are computed the direction for
  58119. */
  58120. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58121. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58122. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58123. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58124. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58125. };
  58126. /**
  58127. * Clones the current emitter and returns a copy of it
  58128. * @returns the new emitter
  58129. */
  58130. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58131. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58132. BABYLON.Tools.DeepCopy(this, newOne);
  58133. return newOne;
  58134. };
  58135. /**
  58136. * Called by the GPUParticleSystem to setup the update shader
  58137. * @param effect defines the update shader
  58138. */
  58139. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58140. effect.setFloat("radius", this.radius);
  58141. effect.setFloat("height", this.height);
  58142. effect.setFloat("radiusRange", this.radiusRange);
  58143. effect.setVector3("direction1", this.direction1);
  58144. effect.setVector3("direction2", this.direction2);
  58145. };
  58146. /**
  58147. * Returns a string to use to update the GPU particles update shader
  58148. * @returns a string containng the defines string
  58149. */
  58150. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58151. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58152. };
  58153. /**
  58154. * Returns the string "CylinderDirectedParticleEmitter"
  58155. * @returns a string containing the class name
  58156. */
  58157. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58158. return "CylinderDirectedParticleEmitter";
  58159. };
  58160. /**
  58161. * Serializes the particle system to a JSON object.
  58162. * @returns the JSON object
  58163. */
  58164. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58165. var serializationObject = _super.prototype.serialize.call(this);
  58166. serializationObject.direction1 = this.direction1.asArray();
  58167. serializationObject.direction2 = this.direction2.asArray();
  58168. return serializationObject;
  58169. };
  58170. /**
  58171. * Parse properties from a JSON object
  58172. * @param serializationObject defines the JSON object
  58173. */
  58174. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58175. _super.prototype.parse.call(this, serializationObject);
  58176. this.direction1.copyFrom(serializationObject.direction1);
  58177. this.direction2.copyFrom(serializationObject.direction2);
  58178. };
  58179. return CylinderDirectedParticleEmitter;
  58180. }(CylinderParticleEmitter));
  58181. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58182. })(BABYLON || (BABYLON = {}));
  58183. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58184. var BABYLON;
  58185. (function (BABYLON) {
  58186. /**
  58187. * Particle emitter emitting particles from the inside of a cone.
  58188. * It emits the particles alongside the cone volume from the base to the particle.
  58189. * The emission direction might be randomized.
  58190. */
  58191. var ConeParticleEmitter = /** @class */ (function () {
  58192. /**
  58193. * Creates a new instance ConeParticleEmitter
  58194. * @param radius the radius of the emission cone (1 by default)
  58195. * @param angles the cone base angle (PI by default)
  58196. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58197. */
  58198. function ConeParticleEmitter(radius, angle,
  58199. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58200. directionRandomizer) {
  58201. if (radius === void 0) { radius = 1; }
  58202. if (angle === void 0) { angle = Math.PI; }
  58203. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58204. this.directionRandomizer = directionRandomizer;
  58205. /**
  58206. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58207. */
  58208. this.radiusRange = 1;
  58209. /**
  58210. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58211. */
  58212. this.heightRange = 1;
  58213. /**
  58214. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58215. */
  58216. this.emitFromSpawnPointOnly = false;
  58217. this.angle = angle;
  58218. this.radius = radius;
  58219. }
  58220. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58221. /**
  58222. * Gets or sets the radius of the emission cone
  58223. */
  58224. get: function () {
  58225. return this._radius;
  58226. },
  58227. set: function (value) {
  58228. this._radius = value;
  58229. this._buildHeight();
  58230. },
  58231. enumerable: true,
  58232. configurable: true
  58233. });
  58234. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58235. /**
  58236. * Gets or sets the angle of the emission cone
  58237. */
  58238. get: function () {
  58239. return this._angle;
  58240. },
  58241. set: function (value) {
  58242. this._angle = value;
  58243. this._buildHeight();
  58244. },
  58245. enumerable: true,
  58246. configurable: true
  58247. });
  58248. ConeParticleEmitter.prototype._buildHeight = function () {
  58249. if (this._angle !== 0) {
  58250. this._height = this._radius / Math.tan(this._angle / 2);
  58251. }
  58252. else {
  58253. this._height = 1;
  58254. }
  58255. };
  58256. /**
  58257. * Called by the particle System when the direction is computed for the created particle.
  58258. * @param worldMatrix is the world matrix of the particle system
  58259. * @param directionToUpdate is the direction vector to update with the result
  58260. * @param particle is the particle we are computed the direction for
  58261. */
  58262. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58263. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58264. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58265. }
  58266. else {
  58267. // measure the direction Vector from the emitter to the particle.
  58268. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58269. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58270. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58271. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58272. direction.x += randX;
  58273. direction.y += randY;
  58274. direction.z += randZ;
  58275. direction.normalize();
  58276. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58277. }
  58278. };
  58279. /**
  58280. * Called by the particle System when the position is computed for the created particle.
  58281. * @param worldMatrix is the world matrix of the particle system
  58282. * @param positionToUpdate is the position vector to update with the result
  58283. * @param particle is the particle we are computed the position for
  58284. */
  58285. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58286. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58287. var h;
  58288. if (!this.emitFromSpawnPointOnly) {
  58289. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58290. // Better distribution in a cone at normal angles.
  58291. h = 1 - h * h;
  58292. }
  58293. else {
  58294. h = 0.0001;
  58295. }
  58296. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58297. radius = radius * h;
  58298. var randX = radius * Math.sin(s);
  58299. var randZ = radius * Math.cos(s);
  58300. var randY = h * this._height;
  58301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58302. };
  58303. /**
  58304. * Clones the current emitter and returns a copy of it
  58305. * @returns the new emitter
  58306. */
  58307. ConeParticleEmitter.prototype.clone = function () {
  58308. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58309. BABYLON.Tools.DeepCopy(this, newOne);
  58310. return newOne;
  58311. };
  58312. /**
  58313. * Called by the GPUParticleSystem to setup the update shader
  58314. * @param effect defines the update shader
  58315. */
  58316. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58317. effect.setFloat2("radius", this._radius, this.radiusRange);
  58318. effect.setFloat("coneAngle", this._angle);
  58319. effect.setFloat2("height", this._height, this.heightRange);
  58320. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58321. };
  58322. /**
  58323. * Returns a string to use to update the GPU particles update shader
  58324. * @returns a string containng the defines string
  58325. */
  58326. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58327. var defines = "#define CONEEMITTER";
  58328. if (this.emitFromSpawnPointOnly) {
  58329. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58330. }
  58331. return defines;
  58332. };
  58333. /**
  58334. * Returns the string "ConeParticleEmitter"
  58335. * @returns a string containing the class name
  58336. */
  58337. ConeParticleEmitter.prototype.getClassName = function () {
  58338. return "ConeParticleEmitter";
  58339. };
  58340. /**
  58341. * Serializes the particle system to a JSON object.
  58342. * @returns the JSON object
  58343. */
  58344. ConeParticleEmitter.prototype.serialize = function () {
  58345. var serializationObject = {};
  58346. serializationObject.type = this.getClassName();
  58347. serializationObject.radius = this._radius;
  58348. serializationObject.angle = this._angle;
  58349. serializationObject.directionRandomizer = this.directionRandomizer;
  58350. return serializationObject;
  58351. };
  58352. /**
  58353. * Parse properties from a JSON object
  58354. * @param serializationObject defines the JSON object
  58355. */
  58356. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58357. this.radius = serializationObject.radius;
  58358. this.angle = serializationObject.angle;
  58359. this.directionRandomizer = serializationObject.directionRandomizer;
  58360. };
  58361. return ConeParticleEmitter;
  58362. }());
  58363. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58364. })(BABYLON || (BABYLON = {}));
  58365. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58366. var BABYLON;
  58367. (function (BABYLON) {
  58368. /**
  58369. * Particle emitter emitting particles from the inside of a sphere.
  58370. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58371. */
  58372. var SphereParticleEmitter = /** @class */ (function () {
  58373. /**
  58374. * Creates a new instance SphereParticleEmitter
  58375. * @param radius the radius of the emission sphere (1 by default)
  58376. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58377. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58378. */
  58379. function SphereParticleEmitter(
  58380. /**
  58381. * The radius of the emission sphere.
  58382. */
  58383. radius,
  58384. /**
  58385. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58386. */
  58387. radiusRange,
  58388. /**
  58389. * How much to randomize the particle direction [0-1].
  58390. */
  58391. directionRandomizer) {
  58392. if (radius === void 0) { radius = 1; }
  58393. if (radiusRange === void 0) { radiusRange = 1; }
  58394. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58395. this.radius = radius;
  58396. this.radiusRange = radiusRange;
  58397. this.directionRandomizer = directionRandomizer;
  58398. }
  58399. /**
  58400. * Called by the particle System when the direction is computed for the created particle.
  58401. * @param worldMatrix is the world matrix of the particle system
  58402. * @param directionToUpdate is the direction vector to update with the result
  58403. * @param particle is the particle we are computed the direction for
  58404. */
  58405. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58406. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58407. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58408. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58409. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58410. direction.x += randX;
  58411. direction.y += randY;
  58412. direction.z += randZ;
  58413. direction.normalize();
  58414. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58415. };
  58416. /**
  58417. * Called by the particle System when the position is computed for the created particle.
  58418. * @param worldMatrix is the world matrix of the particle system
  58419. * @param positionToUpdate is the position vector to update with the result
  58420. * @param particle is the particle we are computed the position for
  58421. */
  58422. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58423. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58424. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58425. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58426. var theta = Math.acos(2 * v - 1);
  58427. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58428. var randY = randRadius * Math.cos(theta);
  58429. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58430. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58431. };
  58432. /**
  58433. * Clones the current emitter and returns a copy of it
  58434. * @returns the new emitter
  58435. */
  58436. SphereParticleEmitter.prototype.clone = function () {
  58437. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58438. BABYLON.Tools.DeepCopy(this, newOne);
  58439. return newOne;
  58440. };
  58441. /**
  58442. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58443. * @param effect defines the update shader
  58444. */
  58445. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58446. effect.setFloat("radius", this.radius);
  58447. effect.setFloat("radiusRange", this.radiusRange);
  58448. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58449. };
  58450. /**
  58451. * Returns a string to use to update the GPU particles update shader
  58452. * @returns a string containng the defines string
  58453. */
  58454. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58455. return "#define SPHEREEMITTER";
  58456. };
  58457. /**
  58458. * Returns the string "SphereParticleEmitter"
  58459. * @returns a string containing the class name
  58460. */
  58461. SphereParticleEmitter.prototype.getClassName = function () {
  58462. return "SphereParticleEmitter";
  58463. };
  58464. /**
  58465. * Serializes the particle system to a JSON object.
  58466. * @returns the JSON object
  58467. */
  58468. SphereParticleEmitter.prototype.serialize = function () {
  58469. var serializationObject = {};
  58470. serializationObject.type = this.getClassName();
  58471. serializationObject.radius = this.radius;
  58472. serializationObject.radiusRange = this.radiusRange;
  58473. serializationObject.directionRandomizer = this.directionRandomizer;
  58474. return serializationObject;
  58475. };
  58476. /**
  58477. * Parse properties from a JSON object
  58478. * @param serializationObject defines the JSON object
  58479. */
  58480. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58481. this.radius = serializationObject.radius;
  58482. this.radiusRange = serializationObject.radiusRange;
  58483. this.directionRandomizer = serializationObject.directionRandomizer;
  58484. };
  58485. return SphereParticleEmitter;
  58486. }());
  58487. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58488. /**
  58489. * Particle emitter emitting particles from the inside of a sphere.
  58490. * It emits the particles randomly between two vectors.
  58491. */
  58492. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58493. __extends(SphereDirectedParticleEmitter, _super);
  58494. /**
  58495. * Creates a new instance SphereDirectedParticleEmitter
  58496. * @param radius the radius of the emission sphere (1 by default)
  58497. * @param direction1 the min limit of the emission direction (up vector by default)
  58498. * @param direction2 the max limit of the emission direction (up vector by default)
  58499. */
  58500. function SphereDirectedParticleEmitter(radius,
  58501. /**
  58502. * The min limit of the emission direction.
  58503. */
  58504. direction1,
  58505. /**
  58506. * The max limit of the emission direction.
  58507. */
  58508. direction2) {
  58509. if (radius === void 0) { radius = 1; }
  58510. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58511. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58512. var _this = _super.call(this, radius) || this;
  58513. _this.direction1 = direction1;
  58514. _this.direction2 = direction2;
  58515. return _this;
  58516. }
  58517. /**
  58518. * Called by the particle System when the direction is computed for the created particle.
  58519. * @param worldMatrix is the world matrix of the particle system
  58520. * @param directionToUpdate is the direction vector to update with the result
  58521. * @param particle is the particle we are computed the direction for
  58522. */
  58523. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58524. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58525. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58526. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58527. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58528. };
  58529. /**
  58530. * Clones the current emitter and returns a copy of it
  58531. * @returns the new emitter
  58532. */
  58533. SphereDirectedParticleEmitter.prototype.clone = function () {
  58534. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58535. BABYLON.Tools.DeepCopy(this, newOne);
  58536. return newOne;
  58537. };
  58538. /**
  58539. * Called by the GPUParticleSystem to setup the update shader
  58540. * @param effect defines the update shader
  58541. */
  58542. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58543. effect.setFloat("radius", this.radius);
  58544. effect.setFloat("radiusRange", this.radiusRange);
  58545. effect.setVector3("direction1", this.direction1);
  58546. effect.setVector3("direction2", this.direction2);
  58547. };
  58548. /**
  58549. * Returns a string to use to update the GPU particles update shader
  58550. * @returns a string containng the defines string
  58551. */
  58552. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58553. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58554. };
  58555. /**
  58556. * Returns the string "SphereDirectedParticleEmitter"
  58557. * @returns a string containing the class name
  58558. */
  58559. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58560. return "SphereDirectedParticleEmitter";
  58561. };
  58562. /**
  58563. * Serializes the particle system to a JSON object.
  58564. * @returns the JSON object
  58565. */
  58566. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58567. var serializationObject = _super.prototype.serialize.call(this);
  58568. serializationObject.direction1 = this.direction1.asArray();
  58569. serializationObject.direction2 = this.direction2.asArray();
  58570. return serializationObject;
  58571. };
  58572. /**
  58573. * Parse properties from a JSON object
  58574. * @param serializationObject defines the JSON object
  58575. */
  58576. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58577. _super.prototype.parse.call(this, serializationObject);
  58578. this.direction1.copyFrom(serializationObject.direction1);
  58579. this.direction2.copyFrom(serializationObject.direction2);
  58580. };
  58581. return SphereDirectedParticleEmitter;
  58582. }(SphereParticleEmitter));
  58583. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58584. })(BABYLON || (BABYLON = {}));
  58585. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58586. var BABYLON;
  58587. (function (BABYLON) {
  58588. /**
  58589. * Particle emitter emitting particles from the inside of a hemisphere.
  58590. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58591. */
  58592. var HemisphericParticleEmitter = /** @class */ (function () {
  58593. /**
  58594. * Creates a new instance HemisphericParticleEmitter
  58595. * @param radius the radius of the emission hemisphere (1 by default)
  58596. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58597. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58598. */
  58599. function HemisphericParticleEmitter(
  58600. /**
  58601. * The radius of the emission hemisphere.
  58602. */
  58603. radius,
  58604. /**
  58605. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58606. */
  58607. radiusRange,
  58608. /**
  58609. * How much to randomize the particle direction [0-1].
  58610. */
  58611. directionRandomizer) {
  58612. if (radius === void 0) { radius = 1; }
  58613. if (radiusRange === void 0) { radiusRange = 1; }
  58614. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58615. this.radius = radius;
  58616. this.radiusRange = radiusRange;
  58617. this.directionRandomizer = directionRandomizer;
  58618. }
  58619. /**
  58620. * Called by the particle System when the direction is computed for the created particle.
  58621. * @param worldMatrix is the world matrix of the particle system
  58622. * @param directionToUpdate is the direction vector to update with the result
  58623. * @param particle is the particle we are computed the direction for
  58624. */
  58625. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58626. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58627. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58628. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58629. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58630. direction.x += randX;
  58631. direction.y += randY;
  58632. direction.z += randZ;
  58633. direction.normalize();
  58634. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58635. };
  58636. /**
  58637. * Called by the particle System when the position is computed for the created particle.
  58638. * @param worldMatrix is the world matrix of the particle system
  58639. * @param positionToUpdate is the position vector to update with the result
  58640. * @param particle is the particle we are computed the position for
  58641. */
  58642. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58643. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58644. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58645. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58646. var theta = Math.acos(2 * v - 1);
  58647. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58648. var randY = randRadius * Math.cos(theta);
  58649. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58650. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58651. };
  58652. /**
  58653. * Clones the current emitter and returns a copy of it
  58654. * @returns the new emitter
  58655. */
  58656. HemisphericParticleEmitter.prototype.clone = function () {
  58657. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58658. BABYLON.Tools.DeepCopy(this, newOne);
  58659. return newOne;
  58660. };
  58661. /**
  58662. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58663. * @param effect defines the update shader
  58664. */
  58665. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58666. effect.setFloat("radius", this.radius);
  58667. effect.setFloat("radiusRange", this.radiusRange);
  58668. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58669. };
  58670. /**
  58671. * Returns a string to use to update the GPU particles update shader
  58672. * @returns a string containng the defines string
  58673. */
  58674. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58675. return "#define HEMISPHERICEMITTER";
  58676. };
  58677. /**
  58678. * Returns the string "HemisphericParticleEmitter"
  58679. * @returns a string containing the class name
  58680. */
  58681. HemisphericParticleEmitter.prototype.getClassName = function () {
  58682. return "HemisphericParticleEmitter";
  58683. };
  58684. /**
  58685. * Serializes the particle system to a JSON object.
  58686. * @returns the JSON object
  58687. */
  58688. HemisphericParticleEmitter.prototype.serialize = function () {
  58689. var serializationObject = {};
  58690. serializationObject.type = this.getClassName();
  58691. serializationObject.radius = this.radius;
  58692. serializationObject.radiusRange = this.radiusRange;
  58693. serializationObject.directionRandomizer = this.directionRandomizer;
  58694. return serializationObject;
  58695. };
  58696. /**
  58697. * Parse properties from a JSON object
  58698. * @param serializationObject defines the JSON object
  58699. */
  58700. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58701. this.radius = serializationObject.radius;
  58702. this.radiusRange = serializationObject.radiusRange;
  58703. this.directionRandomizer = serializationObject.directionRandomizer;
  58704. };
  58705. return HemisphericParticleEmitter;
  58706. }());
  58707. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58708. })(BABYLON || (BABYLON = {}));
  58709. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58710. var BABYLON;
  58711. (function (BABYLON) {
  58712. /**
  58713. * Particle emitter emitting particles from a point.
  58714. * It emits the particles randomly between 2 given directions.
  58715. */
  58716. var PointParticleEmitter = /** @class */ (function () {
  58717. /**
  58718. * Creates a new instance PointParticleEmitter
  58719. */
  58720. function PointParticleEmitter() {
  58721. /**
  58722. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58723. */
  58724. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58725. /**
  58726. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58727. */
  58728. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58729. }
  58730. /**
  58731. * Called by the particle System when the direction is computed for the created particle.
  58732. * @param worldMatrix is the world matrix of the particle system
  58733. * @param directionToUpdate is the direction vector to update with the result
  58734. * @param particle is the particle we are computed the direction for
  58735. */
  58736. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58737. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58738. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58739. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58740. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58741. };
  58742. /**
  58743. * Called by the particle System when the position is computed for the created particle.
  58744. * @param worldMatrix is the world matrix of the particle system
  58745. * @param positionToUpdate is the position vector to update with the result
  58746. * @param particle is the particle we are computed the position for
  58747. */
  58748. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58749. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58750. };
  58751. /**
  58752. * Clones the current emitter and returns a copy of it
  58753. * @returns the new emitter
  58754. */
  58755. PointParticleEmitter.prototype.clone = function () {
  58756. var newOne = new PointParticleEmitter();
  58757. BABYLON.Tools.DeepCopy(this, newOne);
  58758. return newOne;
  58759. };
  58760. /**
  58761. * Called by the GPUParticleSystem to setup the update shader
  58762. * @param effect defines the update shader
  58763. */
  58764. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58765. effect.setVector3("direction1", this.direction1);
  58766. effect.setVector3("direction2", this.direction2);
  58767. };
  58768. /**
  58769. * Returns a string to use to update the GPU particles update shader
  58770. * @returns a string containng the defines string
  58771. */
  58772. PointParticleEmitter.prototype.getEffectDefines = function () {
  58773. return "#define POINTEMITTER";
  58774. };
  58775. /**
  58776. * Returns the string "PointParticleEmitter"
  58777. * @returns a string containing the class name
  58778. */
  58779. PointParticleEmitter.prototype.getClassName = function () {
  58780. return "PointParticleEmitter";
  58781. };
  58782. /**
  58783. * Serializes the particle system to a JSON object.
  58784. * @returns the JSON object
  58785. */
  58786. PointParticleEmitter.prototype.serialize = function () {
  58787. var serializationObject = {};
  58788. serializationObject.type = this.getClassName();
  58789. serializationObject.direction1 = this.direction1.asArray();
  58790. serializationObject.direction2 = this.direction2.asArray();
  58791. return serializationObject;
  58792. };
  58793. /**
  58794. * Parse properties from a JSON object
  58795. * @param serializationObject defines the JSON object
  58796. */
  58797. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58798. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58799. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58800. };
  58801. return PointParticleEmitter;
  58802. }());
  58803. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58804. })(BABYLON || (BABYLON = {}));
  58805. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58806. var BABYLON;
  58807. (function (BABYLON) {
  58808. // Adds the parsers to the scene parsers.
  58809. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58810. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58811. if (!individualParser) {
  58812. return;
  58813. }
  58814. // Particles Systems
  58815. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58816. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58817. var parsedParticleSystem = parsedData.particleSystems[index];
  58818. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58819. }
  58820. }
  58821. });
  58822. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58823. if (parsedParticleSystem.activeParticleCount) {
  58824. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58825. return ps;
  58826. }
  58827. else {
  58828. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58829. return ps;
  58830. }
  58831. });
  58832. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58833. if (uniformsNames === void 0) { uniformsNames = []; }
  58834. if (samplers === void 0) { samplers = []; }
  58835. if (defines === void 0) { defines = ""; }
  58836. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58837. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58838. if (defines.indexOf(" BILLBOARD") === -1) {
  58839. defines += "\n#define BILLBOARD\n";
  58840. }
  58841. if (samplers.indexOf("diffuseSampler") === -1) {
  58842. samplers.push("diffuseSampler");
  58843. }
  58844. return this.createEffect({
  58845. vertex: "particles",
  58846. fragmentElement: fragmentName
  58847. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58848. };
  58849. })(BABYLON || (BABYLON = {}));
  58850. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58851. var BABYLON;
  58852. (function (BABYLON) {
  58853. var ShaderMaterial = /** @class */ (function (_super) {
  58854. __extends(ShaderMaterial, _super);
  58855. function ShaderMaterial(name, scene, shaderPath, options) {
  58856. var _this = _super.call(this, name, scene) || this;
  58857. _this._textures = {};
  58858. _this._textureArrays = {};
  58859. _this._floats = {};
  58860. _this._ints = {};
  58861. _this._floatsArrays = {};
  58862. _this._colors3 = {};
  58863. _this._colors3Arrays = {};
  58864. _this._colors4 = {};
  58865. _this._vectors2 = {};
  58866. _this._vectors3 = {};
  58867. _this._vectors4 = {};
  58868. _this._matrices = {};
  58869. _this._matrices3x3 = {};
  58870. _this._matrices2x2 = {};
  58871. _this._vectors2Arrays = {};
  58872. _this._vectors3Arrays = {};
  58873. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58874. _this._shaderPath = shaderPath;
  58875. options.needAlphaBlending = options.needAlphaBlending || false;
  58876. options.needAlphaTesting = options.needAlphaTesting || false;
  58877. options.attributes = options.attributes || ["position", "normal", "uv"];
  58878. options.uniforms = options.uniforms || ["worldViewProjection"];
  58879. options.uniformBuffers = options.uniformBuffers || [];
  58880. options.samplers = options.samplers || [];
  58881. options.defines = options.defines || [];
  58882. _this._options = options;
  58883. return _this;
  58884. }
  58885. ShaderMaterial.prototype.getClassName = function () {
  58886. return "ShaderMaterial";
  58887. };
  58888. ShaderMaterial.prototype.needAlphaBlending = function () {
  58889. return this._options.needAlphaBlending;
  58890. };
  58891. ShaderMaterial.prototype.needAlphaTesting = function () {
  58892. return this._options.needAlphaTesting;
  58893. };
  58894. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58895. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58896. this._options.uniforms.push(uniformName);
  58897. }
  58898. };
  58899. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58900. if (this._options.samplers.indexOf(name) === -1) {
  58901. this._options.samplers.push(name);
  58902. }
  58903. this._textures[name] = texture;
  58904. return this;
  58905. };
  58906. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58907. if (this._options.samplers.indexOf(name) === -1) {
  58908. this._options.samplers.push(name);
  58909. }
  58910. this._checkUniform(name);
  58911. this._textureArrays[name] = textures;
  58912. return this;
  58913. };
  58914. ShaderMaterial.prototype.setFloat = function (name, value) {
  58915. this._checkUniform(name);
  58916. this._floats[name] = value;
  58917. return this;
  58918. };
  58919. ShaderMaterial.prototype.setInt = function (name, value) {
  58920. this._checkUniform(name);
  58921. this._ints[name] = value;
  58922. return this;
  58923. };
  58924. ShaderMaterial.prototype.setFloats = function (name, value) {
  58925. this._checkUniform(name);
  58926. this._floatsArrays[name] = value;
  58927. return this;
  58928. };
  58929. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58930. this._checkUniform(name);
  58931. this._colors3[name] = value;
  58932. return this;
  58933. };
  58934. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58935. this._checkUniform(name);
  58936. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58937. color.toArray(arr, arr.length);
  58938. return arr;
  58939. }, []);
  58940. return this;
  58941. };
  58942. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58943. this._checkUniform(name);
  58944. this._colors4[name] = value;
  58945. return this;
  58946. };
  58947. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58948. this._checkUniform(name);
  58949. this._vectors2[name] = value;
  58950. return this;
  58951. };
  58952. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58953. this._checkUniform(name);
  58954. this._vectors3[name] = value;
  58955. return this;
  58956. };
  58957. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58958. this._checkUniform(name);
  58959. this._vectors4[name] = value;
  58960. return this;
  58961. };
  58962. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58963. this._checkUniform(name);
  58964. this._matrices[name] = value;
  58965. return this;
  58966. };
  58967. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58968. this._checkUniform(name);
  58969. this._matrices3x3[name] = value;
  58970. return this;
  58971. };
  58972. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58973. this._checkUniform(name);
  58974. this._matrices2x2[name] = value;
  58975. return this;
  58976. };
  58977. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58978. this._checkUniform(name);
  58979. this._vectors2Arrays[name] = value;
  58980. return this;
  58981. };
  58982. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58983. this._checkUniform(name);
  58984. this._vectors3Arrays[name] = value;
  58985. return this;
  58986. };
  58987. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58988. if (!mesh) {
  58989. return true;
  58990. }
  58991. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58992. return false;
  58993. }
  58994. return false;
  58995. };
  58996. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58997. var scene = this.getScene();
  58998. var engine = scene.getEngine();
  58999. if (!this.checkReadyOnEveryCall) {
  59000. if (this._renderId === scene.getRenderId()) {
  59001. if (this._checkCache(scene, mesh, useInstances)) {
  59002. return true;
  59003. }
  59004. }
  59005. }
  59006. // Instances
  59007. var defines = [];
  59008. var attribs = [];
  59009. var fallbacks = new BABYLON.EffectFallbacks();
  59010. if (useInstances) {
  59011. defines.push("#define INSTANCES");
  59012. }
  59013. for (var index = 0; index < this._options.defines.length; index++) {
  59014. defines.push(this._options.defines[index]);
  59015. }
  59016. for (var index = 0; index < this._options.attributes.length; index++) {
  59017. attribs.push(this._options.attributes[index]);
  59018. }
  59019. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59020. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59021. defines.push("#define VERTEXCOLOR");
  59022. }
  59023. // Bones
  59024. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59025. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59026. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59027. if (mesh.numBoneInfluencers > 4) {
  59028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59030. }
  59031. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59032. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59033. fallbacks.addCPUSkinningFallback(0, mesh);
  59034. if (this._options.uniforms.indexOf("mBones") === -1) {
  59035. this._options.uniforms.push("mBones");
  59036. }
  59037. }
  59038. else {
  59039. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59040. }
  59041. // Textures
  59042. for (var name in this._textures) {
  59043. if (!this._textures[name].isReady()) {
  59044. return false;
  59045. }
  59046. }
  59047. // Alpha test
  59048. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59049. defines.push("#define ALPHATEST");
  59050. }
  59051. var previousEffect = this._effect;
  59052. var join = defines.join("\n");
  59053. this._effect = engine.createEffect(this._shaderPath, {
  59054. attributes: attribs,
  59055. uniformsNames: this._options.uniforms,
  59056. uniformBuffersNames: this._options.uniformBuffers,
  59057. samplers: this._options.samplers,
  59058. defines: join,
  59059. fallbacks: fallbacks,
  59060. onCompiled: this.onCompiled,
  59061. onError: this.onError
  59062. }, engine);
  59063. if (!this._effect.isReady()) {
  59064. return false;
  59065. }
  59066. if (previousEffect !== this._effect) {
  59067. scene.resetCachedMaterial();
  59068. }
  59069. this._renderId = scene.getRenderId();
  59070. return true;
  59071. };
  59072. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59073. var scene = this.getScene();
  59074. if (!this._effect) {
  59075. return;
  59076. }
  59077. if (this._options.uniforms.indexOf("world") !== -1) {
  59078. this._effect.setMatrix("world", world);
  59079. }
  59080. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59081. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59082. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59083. }
  59084. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59085. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59086. }
  59087. };
  59088. ShaderMaterial.prototype.bind = function (world, mesh) {
  59089. // Std values
  59090. this.bindOnlyWorldMatrix(world);
  59091. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59092. if (this._options.uniforms.indexOf("view") !== -1) {
  59093. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59094. }
  59095. if (this._options.uniforms.indexOf("projection") !== -1) {
  59096. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59097. }
  59098. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59099. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59100. }
  59101. // Bones
  59102. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59103. var name;
  59104. // Texture
  59105. for (name in this._textures) {
  59106. this._effect.setTexture(name, this._textures[name]);
  59107. }
  59108. // Texture arrays
  59109. for (name in this._textureArrays) {
  59110. this._effect.setTextureArray(name, this._textureArrays[name]);
  59111. }
  59112. // Int
  59113. for (name in this._ints) {
  59114. this._effect.setInt(name, this._ints[name]);
  59115. }
  59116. // Float
  59117. for (name in this._floats) {
  59118. this._effect.setFloat(name, this._floats[name]);
  59119. }
  59120. // Floats
  59121. for (name in this._floatsArrays) {
  59122. this._effect.setArray(name, this._floatsArrays[name]);
  59123. }
  59124. // Color3
  59125. for (name in this._colors3) {
  59126. this._effect.setColor3(name, this._colors3[name]);
  59127. }
  59128. for (name in this._colors3Arrays) {
  59129. this._effect.setArray3(name, this._colors3Arrays[name]);
  59130. }
  59131. // Color4
  59132. for (name in this._colors4) {
  59133. var color = this._colors4[name];
  59134. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59135. }
  59136. // Vector2
  59137. for (name in this._vectors2) {
  59138. this._effect.setVector2(name, this._vectors2[name]);
  59139. }
  59140. // Vector3
  59141. for (name in this._vectors3) {
  59142. this._effect.setVector3(name, this._vectors3[name]);
  59143. }
  59144. // Vector4
  59145. for (name in this._vectors4) {
  59146. this._effect.setVector4(name, this._vectors4[name]);
  59147. }
  59148. // Matrix
  59149. for (name in this._matrices) {
  59150. this._effect.setMatrix(name, this._matrices[name]);
  59151. }
  59152. // Matrix 3x3
  59153. for (name in this._matrices3x3) {
  59154. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59155. }
  59156. // Matrix 2x2
  59157. for (name in this._matrices2x2) {
  59158. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59159. }
  59160. // Vector2Array
  59161. for (name in this._vectors2Arrays) {
  59162. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59163. }
  59164. // Vector3Array
  59165. for (name in this._vectors3Arrays) {
  59166. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59167. }
  59168. }
  59169. this._afterBind(mesh);
  59170. };
  59171. ShaderMaterial.prototype.getActiveTextures = function () {
  59172. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59173. for (var name in this._textures) {
  59174. activeTextures.push(this._textures[name]);
  59175. }
  59176. for (var name in this._textureArrays) {
  59177. var array = this._textureArrays[name];
  59178. for (var index = 0; index < array.length; index++) {
  59179. activeTextures.push(array[index]);
  59180. }
  59181. }
  59182. return activeTextures;
  59183. };
  59184. ShaderMaterial.prototype.hasTexture = function (texture) {
  59185. if (_super.prototype.hasTexture.call(this, texture)) {
  59186. return true;
  59187. }
  59188. for (var name in this._textures) {
  59189. if (this._textures[name] === texture) {
  59190. return true;
  59191. }
  59192. }
  59193. for (var name in this._textureArrays) {
  59194. var array = this._textureArrays[name];
  59195. for (var index = 0; index < array.length; index++) {
  59196. if (array[index] === texture) {
  59197. return true;
  59198. }
  59199. }
  59200. }
  59201. return false;
  59202. };
  59203. ShaderMaterial.prototype.clone = function (name) {
  59204. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59205. return newShaderMaterial;
  59206. };
  59207. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59208. if (forceDisposeTextures) {
  59209. var name;
  59210. for (name in this._textures) {
  59211. this._textures[name].dispose();
  59212. }
  59213. for (name in this._textureArrays) {
  59214. var array = this._textureArrays[name];
  59215. for (var index = 0; index < array.length; index++) {
  59216. array[index].dispose();
  59217. }
  59218. }
  59219. }
  59220. this._textures = {};
  59221. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59222. };
  59223. ShaderMaterial.prototype.serialize = function () {
  59224. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59225. serializationObject.customType = "BABYLON.ShaderMaterial";
  59226. serializationObject.options = this._options;
  59227. serializationObject.shaderPath = this._shaderPath;
  59228. var name;
  59229. // Texture
  59230. serializationObject.textures = {};
  59231. for (name in this._textures) {
  59232. serializationObject.textures[name] = this._textures[name].serialize();
  59233. }
  59234. // Texture arrays
  59235. serializationObject.textureArrays = {};
  59236. for (name in this._textureArrays) {
  59237. serializationObject.textureArrays[name] = [];
  59238. var array = this._textureArrays[name];
  59239. for (var index = 0; index < array.length; index++) {
  59240. serializationObject.textureArrays[name].push(array[index].serialize());
  59241. }
  59242. }
  59243. // Float
  59244. serializationObject.floats = {};
  59245. for (name in this._floats) {
  59246. serializationObject.floats[name] = this._floats[name];
  59247. }
  59248. // Float s
  59249. serializationObject.FloatArrays = {};
  59250. for (name in this._floatsArrays) {
  59251. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59252. }
  59253. // Color3
  59254. serializationObject.colors3 = {};
  59255. for (name in this._colors3) {
  59256. serializationObject.colors3[name] = this._colors3[name].asArray();
  59257. }
  59258. // Color3 array
  59259. serializationObject.colors3Arrays = {};
  59260. for (name in this._colors3Arrays) {
  59261. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59262. }
  59263. // Color4
  59264. serializationObject.colors4 = {};
  59265. for (name in this._colors4) {
  59266. serializationObject.colors4[name] = this._colors4[name].asArray();
  59267. }
  59268. // Vector2
  59269. serializationObject.vectors2 = {};
  59270. for (name in this._vectors2) {
  59271. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59272. }
  59273. // Vector3
  59274. serializationObject.vectors3 = {};
  59275. for (name in this._vectors3) {
  59276. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59277. }
  59278. // Vector4
  59279. serializationObject.vectors4 = {};
  59280. for (name in this._vectors4) {
  59281. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59282. }
  59283. // Matrix
  59284. serializationObject.matrices = {};
  59285. for (name in this._matrices) {
  59286. serializationObject.matrices[name] = this._matrices[name].asArray();
  59287. }
  59288. // Matrix 3x3
  59289. serializationObject.matrices3x3 = {};
  59290. for (name in this._matrices3x3) {
  59291. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59292. }
  59293. // Matrix 2x2
  59294. serializationObject.matrices2x2 = {};
  59295. for (name in this._matrices2x2) {
  59296. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59297. }
  59298. // Vector2Array
  59299. serializationObject.vectors2Arrays = {};
  59300. for (name in this._vectors2Arrays) {
  59301. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59302. }
  59303. // Vector3Array
  59304. serializationObject.vectors3Arrays = {};
  59305. for (name in this._vectors3Arrays) {
  59306. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59307. }
  59308. return serializationObject;
  59309. };
  59310. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59311. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59312. var name;
  59313. // Texture
  59314. for (name in source.textures) {
  59315. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59316. }
  59317. // Texture arrays
  59318. for (name in source.textureArrays) {
  59319. var array = source.textureArrays[name];
  59320. var textureArray = new Array();
  59321. for (var index = 0; index < array.length; index++) {
  59322. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59323. }
  59324. material.setTextureArray(name, textureArray);
  59325. }
  59326. // Float
  59327. for (name in source.floats) {
  59328. material.setFloat(name, source.floats[name]);
  59329. }
  59330. // Float s
  59331. for (name in source.floatsArrays) {
  59332. material.setFloats(name, source.floatsArrays[name]);
  59333. }
  59334. // Color3
  59335. for (name in source.colors3) {
  59336. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59337. }
  59338. // Color3 arrays
  59339. for (name in source.colors3Arrays) {
  59340. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59341. if (i % 3 === 0) {
  59342. arr.push([num]);
  59343. }
  59344. else {
  59345. arr[arr.length - 1].push(num);
  59346. }
  59347. return arr;
  59348. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59349. material.setColor3Array(name, colors);
  59350. }
  59351. // Color4
  59352. for (name in source.colors4) {
  59353. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59354. }
  59355. // Vector2
  59356. for (name in source.vectors2) {
  59357. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59358. }
  59359. // Vector3
  59360. for (name in source.vectors3) {
  59361. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59362. }
  59363. // Vector4
  59364. for (name in source.vectors4) {
  59365. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59366. }
  59367. // Matrix
  59368. for (name in source.matrices) {
  59369. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59370. }
  59371. // Matrix 3x3
  59372. for (name in source.matrices3x3) {
  59373. material.setMatrix3x3(name, source.matrices3x3[name]);
  59374. }
  59375. // Matrix 2x2
  59376. for (name in source.matrices2x2) {
  59377. material.setMatrix2x2(name, source.matrices2x2[name]);
  59378. }
  59379. // Vector2Array
  59380. for (name in source.vectors2Arrays) {
  59381. material.setArray2(name, source.vectors2Arrays[name]);
  59382. }
  59383. // Vector3Array
  59384. for (name in source.vectors3Arrays) {
  59385. material.setArray3(name, source.vectors3Arrays[name]);
  59386. }
  59387. return material;
  59388. };
  59389. return ShaderMaterial;
  59390. }(BABYLON.Material));
  59391. BABYLON.ShaderMaterial = ShaderMaterial;
  59392. })(BABYLON || (BABYLON = {}));
  59393. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59394. var BABYLON;
  59395. (function (BABYLON) {
  59396. var GroundMesh = /** @class */ (function (_super) {
  59397. __extends(GroundMesh, _super);
  59398. function GroundMesh(name, scene) {
  59399. var _this = _super.call(this, name, scene) || this;
  59400. _this.generateOctree = false;
  59401. return _this;
  59402. }
  59403. GroundMesh.prototype.getClassName = function () {
  59404. return "GroundMesh";
  59405. };
  59406. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59407. get: function () {
  59408. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59409. },
  59410. enumerable: true,
  59411. configurable: true
  59412. });
  59413. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59414. get: function () {
  59415. return this._subdivisionsX;
  59416. },
  59417. enumerable: true,
  59418. configurable: true
  59419. });
  59420. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59421. get: function () {
  59422. return this._subdivisionsY;
  59423. },
  59424. enumerable: true,
  59425. configurable: true
  59426. });
  59427. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59428. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59429. this._subdivisionsX = chunksCount;
  59430. this._subdivisionsY = chunksCount;
  59431. this.subdivide(chunksCount);
  59432. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59433. };
  59434. /**
  59435. * Returns a height (y) value in the Worl system :
  59436. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59437. * Returns the ground y position if (x, z) are outside the ground surface.
  59438. */
  59439. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59440. var world = this.getWorldMatrix();
  59441. var invMat = BABYLON.Tmp.Matrix[5];
  59442. world.invertToRef(invMat);
  59443. var tmpVect = BABYLON.Tmp.Vector3[8];
  59444. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59445. x = tmpVect.x;
  59446. z = tmpVect.z;
  59447. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59448. return this.position.y;
  59449. }
  59450. if (!this._heightQuads || this._heightQuads.length == 0) {
  59451. this._initHeightQuads();
  59452. this._computeHeightQuads();
  59453. }
  59454. var facet = this._getFacetAt(x, z);
  59455. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59456. // return y in the World system
  59457. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59458. return tmpVect.y;
  59459. };
  59460. /**
  59461. * Returns a normalized vector (Vector3) orthogonal to the ground
  59462. * at the ground coordinates (x, z) expressed in the World system.
  59463. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59464. */
  59465. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59466. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59467. this.getNormalAtCoordinatesToRef(x, z, normal);
  59468. return normal;
  59469. };
  59470. /**
  59471. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59472. * at the ground coordinates (x, z) expressed in the World system.
  59473. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59474. * Returns the GroundMesh.
  59475. */
  59476. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59477. var world = this.getWorldMatrix();
  59478. var tmpMat = BABYLON.Tmp.Matrix[5];
  59479. world.invertToRef(tmpMat);
  59480. var tmpVect = BABYLON.Tmp.Vector3[8];
  59481. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59482. x = tmpVect.x;
  59483. z = tmpVect.z;
  59484. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59485. return this;
  59486. }
  59487. if (!this._heightQuads || this._heightQuads.length == 0) {
  59488. this._initHeightQuads();
  59489. this._computeHeightQuads();
  59490. }
  59491. var facet = this._getFacetAt(x, z);
  59492. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59493. return this;
  59494. };
  59495. /**
  59496. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59497. * if the ground has been updated.
  59498. * This can be used in the render loop.
  59499. * Returns the GroundMesh.
  59500. */
  59501. GroundMesh.prototype.updateCoordinateHeights = function () {
  59502. if (!this._heightQuads || this._heightQuads.length == 0) {
  59503. this._initHeightQuads();
  59504. }
  59505. this._computeHeightQuads();
  59506. return this;
  59507. };
  59508. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59509. GroundMesh.prototype._getFacetAt = function (x, z) {
  59510. // retrieve col and row from x, z coordinates in the ground local system
  59511. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59512. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59513. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59514. var facet;
  59515. if (z < quad.slope.x * x + quad.slope.y) {
  59516. facet = quad.facet1;
  59517. }
  59518. else {
  59519. facet = quad.facet2;
  59520. }
  59521. return facet;
  59522. };
  59523. // Creates and populates the heightMap array with "facet" elements :
  59524. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59525. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59526. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59527. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59528. // Returns the GroundMesh.
  59529. GroundMesh.prototype._initHeightQuads = function () {
  59530. var subdivisionsX = this._subdivisionsX;
  59531. var subdivisionsY = this._subdivisionsY;
  59532. this._heightQuads = new Array();
  59533. for (var row = 0; row < subdivisionsY; row++) {
  59534. for (var col = 0; col < subdivisionsX; col++) {
  59535. 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) };
  59536. this._heightQuads[row * subdivisionsX + col] = quad;
  59537. }
  59538. }
  59539. return this;
  59540. };
  59541. // Compute each quad element values and update the the heightMap array :
  59542. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59543. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59544. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59545. // Returns the GroundMesh.
  59546. GroundMesh.prototype._computeHeightQuads = function () {
  59547. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59548. if (!positions) {
  59549. return this;
  59550. }
  59551. var v1 = BABYLON.Tmp.Vector3[3];
  59552. var v2 = BABYLON.Tmp.Vector3[2];
  59553. var v3 = BABYLON.Tmp.Vector3[1];
  59554. var v4 = BABYLON.Tmp.Vector3[0];
  59555. var v1v2 = BABYLON.Tmp.Vector3[4];
  59556. var v1v3 = BABYLON.Tmp.Vector3[5];
  59557. var v1v4 = BABYLON.Tmp.Vector3[6];
  59558. var norm1 = BABYLON.Tmp.Vector3[7];
  59559. var norm2 = BABYLON.Tmp.Vector3[8];
  59560. var i = 0;
  59561. var j = 0;
  59562. var k = 0;
  59563. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59564. var h = 0;
  59565. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59566. var d2 = 0;
  59567. var subdivisionsX = this._subdivisionsX;
  59568. var subdivisionsY = this._subdivisionsY;
  59569. for (var row = 0; row < subdivisionsY; row++) {
  59570. for (var col = 0; col < subdivisionsX; col++) {
  59571. i = col * 3;
  59572. j = row * (subdivisionsX + 1) * 3;
  59573. k = (row + 1) * (subdivisionsX + 1) * 3;
  59574. v1.x = positions[j + i];
  59575. v1.y = positions[j + i + 1];
  59576. v1.z = positions[j + i + 2];
  59577. v2.x = positions[j + i + 3];
  59578. v2.y = positions[j + i + 4];
  59579. v2.z = positions[j + i + 5];
  59580. v3.x = positions[k + i];
  59581. v3.y = positions[k + i + 1];
  59582. v3.z = positions[k + i + 2];
  59583. v4.x = positions[k + i + 3];
  59584. v4.y = positions[k + i + 4];
  59585. v4.z = positions[k + i + 5];
  59586. // 2D slope V1V4
  59587. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59588. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59589. // facet equations :
  59590. // we compute each facet normal vector
  59591. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59592. // we compute the value d by applying the equation to v1 which belongs to the plane
  59593. // then we store the facet equation in a Vector4
  59594. v2.subtractToRef(v1, v1v2);
  59595. v3.subtractToRef(v1, v1v3);
  59596. v4.subtractToRef(v1, v1v4);
  59597. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59598. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59599. norm1.normalize();
  59600. norm2.normalize();
  59601. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59602. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59603. var quad = this._heightQuads[row * subdivisionsX + col];
  59604. quad.slope.copyFromFloats(cd, h);
  59605. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59606. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59607. }
  59608. }
  59609. return this;
  59610. };
  59611. GroundMesh.prototype.serialize = function (serializationObject) {
  59612. _super.prototype.serialize.call(this, serializationObject);
  59613. serializationObject.subdivisionsX = this._subdivisionsX;
  59614. serializationObject.subdivisionsY = this._subdivisionsY;
  59615. serializationObject.minX = this._minX;
  59616. serializationObject.maxX = this._maxX;
  59617. serializationObject.minZ = this._minZ;
  59618. serializationObject.maxZ = this._maxZ;
  59619. serializationObject.width = this._width;
  59620. serializationObject.height = this._height;
  59621. };
  59622. GroundMesh.Parse = function (parsedMesh, scene) {
  59623. var result = new GroundMesh(parsedMesh.name, scene);
  59624. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59625. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59626. result._minX = parsedMesh.minX;
  59627. result._maxX = parsedMesh.maxX;
  59628. result._minZ = parsedMesh.minZ;
  59629. result._maxZ = parsedMesh.maxZ;
  59630. result._width = parsedMesh.width;
  59631. result._height = parsedMesh.height;
  59632. return result;
  59633. };
  59634. return GroundMesh;
  59635. }(BABYLON.Mesh));
  59636. BABYLON.GroundMesh = GroundMesh;
  59637. })(BABYLON || (BABYLON = {}));
  59638. //# sourceMappingURL=babylon.groundMesh.js.map
  59639. var BABYLON;
  59640. (function (BABYLON) {
  59641. /**
  59642. * Creates an instance based on a source mesh.
  59643. */
  59644. var InstancedMesh = /** @class */ (function (_super) {
  59645. __extends(InstancedMesh, _super);
  59646. function InstancedMesh(name, source) {
  59647. var _this = _super.call(this, name, source.getScene()) || this;
  59648. source.instances.push(_this);
  59649. _this._sourceMesh = source;
  59650. _this.position.copyFrom(source.position);
  59651. _this.rotation.copyFrom(source.rotation);
  59652. _this.scaling.copyFrom(source.scaling);
  59653. if (source.rotationQuaternion) {
  59654. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59655. }
  59656. _this.infiniteDistance = source.infiniteDistance;
  59657. _this.setPivotMatrix(source.getPivotMatrix());
  59658. _this.refreshBoundingInfo();
  59659. _this._syncSubMeshes();
  59660. return _this;
  59661. }
  59662. /**
  59663. * Returns the string "InstancedMesh".
  59664. */
  59665. InstancedMesh.prototype.getClassName = function () {
  59666. return "InstancedMesh";
  59667. };
  59668. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59669. // Methods
  59670. get: function () {
  59671. return this._sourceMesh.receiveShadows;
  59672. },
  59673. enumerable: true,
  59674. configurable: true
  59675. });
  59676. Object.defineProperty(InstancedMesh.prototype, "material", {
  59677. get: function () {
  59678. return this._sourceMesh.material;
  59679. },
  59680. enumerable: true,
  59681. configurable: true
  59682. });
  59683. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59684. get: function () {
  59685. return this._sourceMesh.visibility;
  59686. },
  59687. enumerable: true,
  59688. configurable: true
  59689. });
  59690. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59691. get: function () {
  59692. return this._sourceMesh.skeleton;
  59693. },
  59694. enumerable: true,
  59695. configurable: true
  59696. });
  59697. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59698. get: function () {
  59699. return this._sourceMesh.renderingGroupId;
  59700. },
  59701. set: function (value) {
  59702. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59703. return;
  59704. }
  59705. //no-op with warning
  59706. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59707. },
  59708. enumerable: true,
  59709. configurable: true
  59710. });
  59711. /**
  59712. * Returns the total number of vertices (integer).
  59713. */
  59714. InstancedMesh.prototype.getTotalVertices = function () {
  59715. return this._sourceMesh.getTotalVertices();
  59716. };
  59717. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59718. get: function () {
  59719. return this._sourceMesh;
  59720. },
  59721. enumerable: true,
  59722. configurable: true
  59723. });
  59724. /**
  59725. * Is this node ready to be used/rendered
  59726. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59727. * @return {boolean} is it ready
  59728. */
  59729. InstancedMesh.prototype.isReady = function (completeCheck) {
  59730. if (completeCheck === void 0) { completeCheck = false; }
  59731. return this._sourceMesh.isReady(completeCheck, true);
  59732. };
  59733. /**
  59734. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59735. */
  59736. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59737. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59738. };
  59739. /**
  59740. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59741. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59742. * The `data` are either a numeric array either a Float32Array.
  59743. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59744. * 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).
  59745. * Note that a new underlying VertexBuffer object is created each call.
  59746. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59747. *
  59748. * Possible `kind` values :
  59749. * - BABYLON.VertexBuffer.PositionKind
  59750. * - BABYLON.VertexBuffer.UVKind
  59751. * - BABYLON.VertexBuffer.UV2Kind
  59752. * - BABYLON.VertexBuffer.UV3Kind
  59753. * - BABYLON.VertexBuffer.UV4Kind
  59754. * - BABYLON.VertexBuffer.UV5Kind
  59755. * - BABYLON.VertexBuffer.UV6Kind
  59756. * - BABYLON.VertexBuffer.ColorKind
  59757. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59758. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59759. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59760. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59761. *
  59762. * Returns the Mesh.
  59763. */
  59764. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59765. if (this.sourceMesh) {
  59766. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59767. }
  59768. return this.sourceMesh;
  59769. };
  59770. /**
  59771. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59772. * If the mesh has no geometry, it is simply returned as it is.
  59773. * The `data` are either a numeric array either a Float32Array.
  59774. * No new underlying VertexBuffer object is created.
  59775. * 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.
  59776. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59777. *
  59778. * Possible `kind` values :
  59779. * - BABYLON.VertexBuffer.PositionKind
  59780. * - BABYLON.VertexBuffer.UVKind
  59781. * - BABYLON.VertexBuffer.UV2Kind
  59782. * - BABYLON.VertexBuffer.UV3Kind
  59783. * - BABYLON.VertexBuffer.UV4Kind
  59784. * - BABYLON.VertexBuffer.UV5Kind
  59785. * - BABYLON.VertexBuffer.UV6Kind
  59786. * - BABYLON.VertexBuffer.ColorKind
  59787. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59788. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59789. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59790. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59791. *
  59792. * Returns the Mesh.
  59793. */
  59794. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59795. if (this.sourceMesh) {
  59796. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59797. }
  59798. return this.sourceMesh;
  59799. };
  59800. /**
  59801. * Sets the mesh indices.
  59802. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59803. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59804. * This method creates a new index buffer each call.
  59805. * Returns the Mesh.
  59806. */
  59807. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59808. if (totalVertices === void 0) { totalVertices = null; }
  59809. if (this.sourceMesh) {
  59810. this.sourceMesh.setIndices(indices, totalVertices);
  59811. }
  59812. return this.sourceMesh;
  59813. };
  59814. /**
  59815. * Boolean : True if the mesh owns the requested kind of data.
  59816. */
  59817. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59818. return this._sourceMesh.isVerticesDataPresent(kind);
  59819. };
  59820. /**
  59821. * Returns an array of indices (IndicesArray).
  59822. */
  59823. InstancedMesh.prototype.getIndices = function () {
  59824. return this._sourceMesh.getIndices();
  59825. };
  59826. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59827. get: function () {
  59828. return this._sourceMesh._positions;
  59829. },
  59830. enumerable: true,
  59831. configurable: true
  59832. });
  59833. /**
  59834. * Sets a new updated BoundingInfo to the mesh.
  59835. * Returns the mesh.
  59836. */
  59837. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59838. var meshBB = this._sourceMesh.getBoundingInfo();
  59839. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59840. this._updateBoundingInfo();
  59841. return this;
  59842. };
  59843. /** @hidden */
  59844. InstancedMesh.prototype._preActivate = function () {
  59845. if (this._currentLOD) {
  59846. this._currentLOD._preActivate();
  59847. }
  59848. return this;
  59849. };
  59850. /** @hidden */
  59851. InstancedMesh.prototype._activate = function (renderId) {
  59852. if (this._currentLOD) {
  59853. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59854. }
  59855. return this;
  59856. };
  59857. /**
  59858. * Returns the current associated LOD AbstractMesh.
  59859. */
  59860. InstancedMesh.prototype.getLOD = function (camera) {
  59861. if (!camera) {
  59862. return this;
  59863. }
  59864. var boundingInfo = this.getBoundingInfo();
  59865. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59866. if (this._currentLOD === this.sourceMesh) {
  59867. return this;
  59868. }
  59869. return this._currentLOD;
  59870. };
  59871. /** @hidden */
  59872. InstancedMesh.prototype._syncSubMeshes = function () {
  59873. this.releaseSubMeshes();
  59874. if (this._sourceMesh.subMeshes) {
  59875. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59876. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59877. }
  59878. }
  59879. return this;
  59880. };
  59881. /** @hidden */
  59882. InstancedMesh.prototype._generatePointsArray = function () {
  59883. return this._sourceMesh._generatePointsArray();
  59884. };
  59885. /**
  59886. * Creates a new InstancedMesh from the current mesh.
  59887. * - name (string) : the cloned mesh name
  59888. * - newParent (optional Node) : the optional Node to parent the clone to.
  59889. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59890. *
  59891. * Returns the clone.
  59892. */
  59893. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59894. var result = this._sourceMesh.createInstance(name);
  59895. // Deep copy
  59896. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59897. // Bounding info
  59898. this.refreshBoundingInfo();
  59899. // Parent
  59900. if (newParent) {
  59901. result.parent = newParent;
  59902. }
  59903. if (!doNotCloneChildren) {
  59904. // Children
  59905. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59906. var mesh = this.getScene().meshes[index];
  59907. if (mesh.parent === this) {
  59908. mesh.clone(mesh.name, result);
  59909. }
  59910. }
  59911. }
  59912. result.computeWorldMatrix(true);
  59913. return result;
  59914. };
  59915. /**
  59916. * Disposes the InstancedMesh.
  59917. * Returns nothing.
  59918. */
  59919. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59920. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59921. // Remove from mesh
  59922. var index = this._sourceMesh.instances.indexOf(this);
  59923. this._sourceMesh.instances.splice(index, 1);
  59924. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59925. };
  59926. return InstancedMesh;
  59927. }(BABYLON.AbstractMesh));
  59928. BABYLON.InstancedMesh = InstancedMesh;
  59929. })(BABYLON || (BABYLON = {}));
  59930. //# sourceMappingURL=babylon.instancedMesh.js.map
  59931. var BABYLON;
  59932. (function (BABYLON) {
  59933. var LinesMesh = /** @class */ (function (_super) {
  59934. __extends(LinesMesh, _super);
  59935. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59936. if (scene === void 0) { scene = null; }
  59937. if (parent === void 0) { parent = null; }
  59938. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59939. _this.useVertexColor = useVertexColor;
  59940. _this.useVertexAlpha = useVertexAlpha;
  59941. _this.color = new BABYLON.Color3(1, 1, 1);
  59942. _this.alpha = 1;
  59943. if (source) {
  59944. _this.color = source.color.clone();
  59945. _this.alpha = source.alpha;
  59946. _this.useVertexColor = source.useVertexColor;
  59947. _this.useVertexAlpha = source.useVertexAlpha;
  59948. }
  59949. _this._intersectionThreshold = 0.1;
  59950. var defines = [];
  59951. var options = {
  59952. attributes: [BABYLON.VertexBuffer.PositionKind],
  59953. uniforms: ["world", "viewProjection"],
  59954. needAlphaBlending: true,
  59955. defines: defines
  59956. };
  59957. if (useVertexAlpha === false) {
  59958. options.needAlphaBlending = false;
  59959. }
  59960. if (!useVertexColor) {
  59961. options.uniforms.push("color");
  59962. }
  59963. else {
  59964. options.defines.push("#define VERTEXCOLOR");
  59965. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59966. }
  59967. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59968. return _this;
  59969. }
  59970. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59971. /**
  59972. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59973. * This margin is expressed in world space coordinates, so its value may vary.
  59974. * Default value is 0.1
  59975. * @returns the intersection Threshold value.
  59976. */
  59977. get: function () {
  59978. return this._intersectionThreshold;
  59979. },
  59980. /**
  59981. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59982. * This margin is expressed in world space coordinates, so its value may vary.
  59983. * @param value the new threshold to apply
  59984. */
  59985. set: function (value) {
  59986. if (this._intersectionThreshold === value) {
  59987. return;
  59988. }
  59989. this._intersectionThreshold = value;
  59990. if (this.geometry) {
  59991. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59992. }
  59993. },
  59994. enumerable: true,
  59995. configurable: true
  59996. });
  59997. /**
  59998. * Returns the string "LineMesh"
  59999. */
  60000. LinesMesh.prototype.getClassName = function () {
  60001. return "LinesMesh";
  60002. };
  60003. Object.defineProperty(LinesMesh.prototype, "material", {
  60004. /**
  60005. * @hidden
  60006. */
  60007. get: function () {
  60008. return this._colorShader;
  60009. },
  60010. /**
  60011. * @hidden
  60012. */
  60013. set: function (value) {
  60014. // Do nothing
  60015. },
  60016. enumerable: true,
  60017. configurable: true
  60018. });
  60019. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60020. /**
  60021. * @hidden
  60022. */
  60023. get: function () {
  60024. return false;
  60025. },
  60026. enumerable: true,
  60027. configurable: true
  60028. });
  60029. LinesMesh.prototype.createInstance = function (name) {
  60030. throw new Error("LinesMeshes do not support createInstance.");
  60031. };
  60032. /** @hidden */
  60033. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60034. if (!this._geometry) {
  60035. return this;
  60036. }
  60037. // VBOs
  60038. this._geometry._bind(this._colorShader.getEffect());
  60039. // Color
  60040. if (!this.useVertexColor) {
  60041. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60042. }
  60043. return this;
  60044. };
  60045. /** @hidden */
  60046. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60047. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60048. return this;
  60049. }
  60050. var engine = this.getScene().getEngine();
  60051. // Draw order
  60052. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60053. return this;
  60054. };
  60055. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60056. this._colorShader.dispose();
  60057. _super.prototype.dispose.call(this, doNotRecurse);
  60058. };
  60059. /**
  60060. * Returns a new LineMesh object cloned from the current one.
  60061. */
  60062. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60063. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60064. };
  60065. return LinesMesh;
  60066. }(BABYLON.Mesh));
  60067. BABYLON.LinesMesh = LinesMesh;
  60068. })(BABYLON || (BABYLON = {}));
  60069. //# sourceMappingURL=babylon.linesMesh.js.map
  60070. var BABYLON;
  60071. (function (BABYLON) {
  60072. /**
  60073. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60074. * The underlying implementation relies on an associative array to ensure the best performances.
  60075. * The value can be anything including 'null' but except 'undefined'
  60076. */
  60077. var StringDictionary = /** @class */ (function () {
  60078. function StringDictionary() {
  60079. this._count = 0;
  60080. this._data = {};
  60081. }
  60082. /**
  60083. * This will clear this dictionary and copy the content from the 'source' one.
  60084. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60085. * @param source the dictionary to take the content from and copy to this dictionary
  60086. */
  60087. StringDictionary.prototype.copyFrom = function (source) {
  60088. var _this = this;
  60089. this.clear();
  60090. source.forEach(function (t, v) { return _this.add(t, v); });
  60091. };
  60092. /**
  60093. * Get a value based from its key
  60094. * @param key the given key to get the matching value from
  60095. * @return the value if found, otherwise undefined is returned
  60096. */
  60097. StringDictionary.prototype.get = function (key) {
  60098. var val = this._data[key];
  60099. if (val !== undefined) {
  60100. return val;
  60101. }
  60102. return undefined;
  60103. };
  60104. /**
  60105. * Get a value from its key or add it if it doesn't exist.
  60106. * This method will ensure you that a given key/data will be present in the dictionary.
  60107. * @param key the given key to get the matching value from
  60108. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60109. * The factory will only be invoked if there's no data for the given key.
  60110. * @return the value corresponding to the key.
  60111. */
  60112. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60113. var val = this.get(key);
  60114. if (val !== undefined) {
  60115. return val;
  60116. }
  60117. val = factory(key);
  60118. if (val) {
  60119. this.add(key, val);
  60120. }
  60121. return val;
  60122. };
  60123. /**
  60124. * Get a value from its key if present in the dictionary otherwise add it
  60125. * @param key the key to get the value from
  60126. * @param val if there's no such key/value pair in the dictionary add it with this value
  60127. * @return the value corresponding to the key
  60128. */
  60129. StringDictionary.prototype.getOrAdd = function (key, val) {
  60130. var curVal = this.get(key);
  60131. if (curVal !== undefined) {
  60132. return curVal;
  60133. }
  60134. this.add(key, val);
  60135. return val;
  60136. };
  60137. /**
  60138. * Check if there's a given key in the dictionary
  60139. * @param key the key to check for
  60140. * @return true if the key is present, false otherwise
  60141. */
  60142. StringDictionary.prototype.contains = function (key) {
  60143. return this._data[key] !== undefined;
  60144. };
  60145. /**
  60146. * Add a new key and its corresponding value
  60147. * @param key the key to add
  60148. * @param value the value corresponding to the key
  60149. * @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
  60150. */
  60151. StringDictionary.prototype.add = function (key, value) {
  60152. if (this._data[key] !== undefined) {
  60153. return false;
  60154. }
  60155. this._data[key] = value;
  60156. ++this._count;
  60157. return true;
  60158. };
  60159. StringDictionary.prototype.set = function (key, value) {
  60160. if (this._data[key] === undefined) {
  60161. return false;
  60162. }
  60163. this._data[key] = value;
  60164. return true;
  60165. };
  60166. /**
  60167. * Get the element of the given key and remove it from the dictionary
  60168. * @param key
  60169. */
  60170. StringDictionary.prototype.getAndRemove = function (key) {
  60171. var val = this.get(key);
  60172. if (val !== undefined) {
  60173. delete this._data[key];
  60174. --this._count;
  60175. return val;
  60176. }
  60177. return null;
  60178. };
  60179. /**
  60180. * Remove a key/value from the dictionary.
  60181. * @param key the key to remove
  60182. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60183. */
  60184. StringDictionary.prototype.remove = function (key) {
  60185. if (this.contains(key)) {
  60186. delete this._data[key];
  60187. --this._count;
  60188. return true;
  60189. }
  60190. return false;
  60191. };
  60192. /**
  60193. * Clear the whole content of the dictionary
  60194. */
  60195. StringDictionary.prototype.clear = function () {
  60196. this._data = {};
  60197. this._count = 0;
  60198. };
  60199. Object.defineProperty(StringDictionary.prototype, "count", {
  60200. get: function () {
  60201. return this._count;
  60202. },
  60203. enumerable: true,
  60204. configurable: true
  60205. });
  60206. /**
  60207. * Execute a callback on each key/val of the dictionary.
  60208. * Note that you can remove any element in this dictionary in the callback implementation
  60209. * @param callback the callback to execute on a given key/value pair
  60210. */
  60211. StringDictionary.prototype.forEach = function (callback) {
  60212. for (var cur in this._data) {
  60213. var val = this._data[cur];
  60214. callback(cur, val);
  60215. }
  60216. };
  60217. /**
  60218. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60219. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60220. * Note that you can remove any element in this dictionary in the callback implementation
  60221. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60222. */
  60223. StringDictionary.prototype.first = function (callback) {
  60224. for (var cur in this._data) {
  60225. var val = this._data[cur];
  60226. var res = callback(cur, val);
  60227. if (res) {
  60228. return res;
  60229. }
  60230. }
  60231. return null;
  60232. };
  60233. return StringDictionary;
  60234. }());
  60235. BABYLON.StringDictionary = StringDictionary;
  60236. })(BABYLON || (BABYLON = {}));
  60237. //# sourceMappingURL=babylon.stringDictionary.js.map
  60238. var BABYLON;
  60239. (function (BABYLON) {
  60240. var Debug;
  60241. (function (Debug) {
  60242. /**
  60243. * Class used to render a debug view of a given skeleton
  60244. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60245. */
  60246. var SkeletonViewer = /** @class */ (function () {
  60247. /**
  60248. * Creates a new SkeletonViewer
  60249. * @param skeleton defines the skeleton to render
  60250. * @param mesh defines the mesh attached to the skeleton
  60251. * @param scene defines the hosting scene
  60252. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60253. * @param renderingGroupId defines the rendering group id to use with the viewer
  60254. */
  60255. function SkeletonViewer(
  60256. /** defines the skeleton to render */
  60257. skeleton,
  60258. /** defines the mesh attached to the skeleton */
  60259. mesh, scene,
  60260. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60261. autoUpdateBonesMatrices,
  60262. /** defines the rendering group id to use with the viewer */
  60263. renderingGroupId) {
  60264. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60265. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60266. this.skeleton = skeleton;
  60267. this.mesh = mesh;
  60268. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60269. this.renderingGroupId = renderingGroupId;
  60270. /** Gets or sets the color used to render the skeleton */
  60271. this.color = BABYLON.Color3.White();
  60272. this._debugLines = new Array();
  60273. this._isEnabled = false;
  60274. this._scene = scene;
  60275. this.update();
  60276. this._renderFunction = this.update.bind(this);
  60277. }
  60278. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60279. get: function () {
  60280. return this._isEnabled;
  60281. },
  60282. /** Gets or sets a boolean indicating if the viewer is enabled */
  60283. set: function (value) {
  60284. if (this._isEnabled === value) {
  60285. return;
  60286. }
  60287. this._isEnabled = value;
  60288. if (value) {
  60289. this._scene.registerBeforeRender(this._renderFunction);
  60290. }
  60291. else {
  60292. this._scene.unregisterBeforeRender(this._renderFunction);
  60293. }
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60299. if (x === void 0) { x = 0; }
  60300. if (y === void 0) { y = 0; }
  60301. if (z === void 0) { z = 0; }
  60302. var tmat = BABYLON.Tmp.Matrix[0];
  60303. var parentBone = bone.getParent();
  60304. tmat.copyFrom(bone.getLocalMatrix());
  60305. if (x !== 0 || y !== 0 || z !== 0) {
  60306. var tmat2 = BABYLON.Tmp.Matrix[1];
  60307. BABYLON.Matrix.IdentityToRef(tmat2);
  60308. tmat2.m[12] = x;
  60309. tmat2.m[13] = y;
  60310. tmat2.m[14] = z;
  60311. tmat2.multiplyToRef(tmat, tmat);
  60312. }
  60313. if (parentBone) {
  60314. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60315. }
  60316. tmat.multiplyToRef(meshMat, tmat);
  60317. position.x = tmat.m[12];
  60318. position.y = tmat.m[13];
  60319. position.z = tmat.m[14];
  60320. };
  60321. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60322. var len = bones.length;
  60323. var meshPos = this.mesh.position;
  60324. for (var i = 0; i < len; i++) {
  60325. var bone = bones[i];
  60326. var points = this._debugLines[i];
  60327. if (!points) {
  60328. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60329. this._debugLines[i] = points;
  60330. }
  60331. this._getBonePosition(points[0], bone, meshMat);
  60332. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60333. points[0].subtractInPlace(meshPos);
  60334. points[1].subtractInPlace(meshPos);
  60335. }
  60336. };
  60337. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60338. var len = bones.length;
  60339. var boneNum = 0;
  60340. var meshPos = this.mesh.position;
  60341. for (var i = len - 1; i >= 0; i--) {
  60342. var childBone = bones[i];
  60343. var parentBone = childBone.getParent();
  60344. if (!parentBone) {
  60345. continue;
  60346. }
  60347. var points = this._debugLines[boneNum];
  60348. if (!points) {
  60349. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60350. this._debugLines[boneNum] = points;
  60351. }
  60352. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60353. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60354. points[0].subtractInPlace(meshPos);
  60355. points[1].subtractInPlace(meshPos);
  60356. boneNum++;
  60357. }
  60358. };
  60359. /** Update the viewer to sync with current skeleton state */
  60360. SkeletonViewer.prototype.update = function () {
  60361. if (this.autoUpdateBonesMatrices) {
  60362. this.skeleton.computeAbsoluteTransforms();
  60363. }
  60364. if (this.skeleton.bones[0].length === undefined) {
  60365. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60366. }
  60367. else {
  60368. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60369. }
  60370. if (!this._debugMesh) {
  60371. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60372. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60373. }
  60374. else {
  60375. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60376. }
  60377. this._debugMesh.position.copyFrom(this.mesh.position);
  60378. this._debugMesh.color = this.color;
  60379. };
  60380. /** Release associated resources */
  60381. SkeletonViewer.prototype.dispose = function () {
  60382. if (this._debugMesh) {
  60383. this.isEnabled = false;
  60384. this._debugMesh.dispose();
  60385. this._debugMesh = null;
  60386. }
  60387. };
  60388. return SkeletonViewer;
  60389. }());
  60390. Debug.SkeletonViewer = SkeletonViewer;
  60391. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60392. })(BABYLON || (BABYLON = {}));
  60393. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60394. /**
  60395. * Module Debug contains the (visual) components to debug a scene correctly
  60396. */
  60397. var BABYLON;
  60398. (function (BABYLON) {
  60399. var Debug;
  60400. (function (Debug) {
  60401. /**
  60402. * The Axes viewer will show 3 axes in a specific point in space
  60403. */
  60404. var AxesViewer = /** @class */ (function () {
  60405. /**
  60406. * Creates a new AxesViewer
  60407. * @param scene defines the hosting scene
  60408. * @param scaleLines defines a number used to scale line length (1 by default)
  60409. */
  60410. function AxesViewer(scene, scaleLines) {
  60411. if (scaleLines === void 0) { scaleLines = 1; }
  60412. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60413. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60414. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60415. /**
  60416. * Gets or sets a number used to scale line length
  60417. */
  60418. this.scaleLines = 1;
  60419. this.scaleLines = scaleLines;
  60420. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60421. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60422. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60423. this._xmesh.renderingGroupId = 2;
  60424. this._ymesh.renderingGroupId = 2;
  60425. this._zmesh.renderingGroupId = 2;
  60426. this._xmesh.material.checkReadyOnlyOnce = true;
  60427. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60428. this._ymesh.material.checkReadyOnlyOnce = true;
  60429. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60430. this._zmesh.material.checkReadyOnlyOnce = true;
  60431. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60432. this.scene = scene;
  60433. }
  60434. /**
  60435. * Force the viewer to update
  60436. * @param position defines the position of the viewer
  60437. * @param xaxis defines the x axis of the viewer
  60438. * @param yaxis defines the y axis of the viewer
  60439. * @param zaxis defines the z axis of the viewer
  60440. */
  60441. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60442. var scaleLines = this.scaleLines;
  60443. if (this._xmesh) {
  60444. this._xmesh.position.copyFrom(position);
  60445. }
  60446. if (this._ymesh) {
  60447. this._ymesh.position.copyFrom(position);
  60448. }
  60449. if (this._zmesh) {
  60450. this._zmesh.position.copyFrom(position);
  60451. }
  60452. var point2 = this._xline[1];
  60453. point2.x = xaxis.x * scaleLines;
  60454. point2.y = xaxis.y * scaleLines;
  60455. point2.z = xaxis.z * scaleLines;
  60456. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60457. point2 = this._yline[1];
  60458. point2.x = yaxis.x * scaleLines;
  60459. point2.y = yaxis.y * scaleLines;
  60460. point2.z = yaxis.z * scaleLines;
  60461. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60462. point2 = this._zline[1];
  60463. point2.x = zaxis.x * scaleLines;
  60464. point2.y = zaxis.y * scaleLines;
  60465. point2.z = zaxis.z * scaleLines;
  60466. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60467. };
  60468. /** Releases resources */
  60469. AxesViewer.prototype.dispose = function () {
  60470. if (this._xmesh) {
  60471. this._xmesh.dispose();
  60472. }
  60473. if (this._ymesh) {
  60474. this._ymesh.dispose();
  60475. }
  60476. if (this._zmesh) {
  60477. this._zmesh.dispose();
  60478. }
  60479. this._xmesh = null;
  60480. this._ymesh = null;
  60481. this._zmesh = null;
  60482. this.scene = null;
  60483. };
  60484. return AxesViewer;
  60485. }());
  60486. Debug.AxesViewer = AxesViewer;
  60487. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60488. })(BABYLON || (BABYLON = {}));
  60489. //# sourceMappingURL=babylon.axesViewer.js.map
  60490. var BABYLON;
  60491. (function (BABYLON) {
  60492. var Debug;
  60493. (function (Debug) {
  60494. /**
  60495. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60496. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60497. */
  60498. var BoneAxesViewer = /** @class */ (function (_super) {
  60499. __extends(BoneAxesViewer, _super);
  60500. /**
  60501. * Creates a new BoneAxesViewer
  60502. * @param scene defines the hosting scene
  60503. * @param bone defines the target bone
  60504. * @param mesh defines the target mesh
  60505. * @param scaleLines defines a scaling factor for line length (1 by default)
  60506. */
  60507. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60508. if (scaleLines === void 0) { scaleLines = 1; }
  60509. var _this = _super.call(this, scene, scaleLines) || this;
  60510. /** Gets current position */
  60511. _this.pos = BABYLON.Vector3.Zero();
  60512. /** Gets direction of X axis */
  60513. _this.xaxis = BABYLON.Vector3.Zero();
  60514. /** Gets direction of Y axis */
  60515. _this.yaxis = BABYLON.Vector3.Zero();
  60516. /** Gets direction of Z axis */
  60517. _this.zaxis = BABYLON.Vector3.Zero();
  60518. _this.mesh = mesh;
  60519. _this.bone = bone;
  60520. return _this;
  60521. }
  60522. /**
  60523. * Force the viewer to update
  60524. */
  60525. BoneAxesViewer.prototype.update = function () {
  60526. if (!this.mesh || !this.bone) {
  60527. return;
  60528. }
  60529. var bone = this.bone;
  60530. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60531. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60532. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60533. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60534. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60535. };
  60536. /** Releases resources */
  60537. BoneAxesViewer.prototype.dispose = function () {
  60538. if (this.mesh) {
  60539. this.mesh = null;
  60540. this.bone = null;
  60541. _super.prototype.dispose.call(this);
  60542. }
  60543. };
  60544. return BoneAxesViewer;
  60545. }(Debug.AxesViewer));
  60546. Debug.BoneAxesViewer = BoneAxesViewer;
  60547. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60548. })(BABYLON || (BABYLON = {}));
  60549. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60550. var BABYLON;
  60551. (function (BABYLON) {
  60552. var RayHelper = /** @class */ (function () {
  60553. function RayHelper(ray) {
  60554. this.ray = ray;
  60555. }
  60556. RayHelper.CreateAndShow = function (ray, scene, color) {
  60557. var helper = new RayHelper(ray);
  60558. helper.show(scene, color);
  60559. return helper;
  60560. };
  60561. RayHelper.prototype.show = function (scene, color) {
  60562. if (!this._renderFunction && this.ray) {
  60563. var ray = this.ray;
  60564. this._renderFunction = this._render.bind(this);
  60565. this._scene = scene;
  60566. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60567. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60568. if (this._renderFunction) {
  60569. this._scene.registerBeforeRender(this._renderFunction);
  60570. }
  60571. }
  60572. if (color && this._renderLine) {
  60573. this._renderLine.color.copyFrom(color);
  60574. }
  60575. };
  60576. RayHelper.prototype.hide = function () {
  60577. if (this._renderFunction && this._scene) {
  60578. this._scene.unregisterBeforeRender(this._renderFunction);
  60579. this._scene = null;
  60580. this._renderFunction = null;
  60581. if (this._renderLine) {
  60582. this._renderLine.dispose();
  60583. this._renderLine = null;
  60584. }
  60585. this._renderPoints = [];
  60586. }
  60587. };
  60588. RayHelper.prototype._render = function () {
  60589. var ray = this.ray;
  60590. if (!ray) {
  60591. return;
  60592. }
  60593. var point = this._renderPoints[1];
  60594. var len = Math.min(ray.length, 1000000);
  60595. point.copyFrom(ray.direction);
  60596. point.scaleInPlace(len);
  60597. point.addInPlace(ray.origin);
  60598. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60599. };
  60600. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60601. this._attachedToMesh = mesh;
  60602. var ray = this.ray;
  60603. if (!ray) {
  60604. return;
  60605. }
  60606. if (!ray.direction) {
  60607. ray.direction = BABYLON.Vector3.Zero();
  60608. }
  60609. if (!ray.origin) {
  60610. ray.origin = BABYLON.Vector3.Zero();
  60611. }
  60612. if (length) {
  60613. ray.length = length;
  60614. }
  60615. if (!meshSpaceOrigin) {
  60616. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60617. }
  60618. if (!meshSpaceDirection) {
  60619. // -1 so that this will work with Mesh.lookAt
  60620. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60621. }
  60622. if (!this._meshSpaceDirection) {
  60623. this._meshSpaceDirection = meshSpaceDirection.clone();
  60624. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60625. }
  60626. else {
  60627. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60628. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60629. }
  60630. if (!this._updateToMeshFunction) {
  60631. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60632. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60633. }
  60634. this._updateToMesh();
  60635. };
  60636. RayHelper.prototype.detachFromMesh = function () {
  60637. if (this._attachedToMesh) {
  60638. if (this._updateToMeshFunction) {
  60639. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60640. }
  60641. this._attachedToMesh = null;
  60642. this._updateToMeshFunction = null;
  60643. }
  60644. };
  60645. RayHelper.prototype._updateToMesh = function () {
  60646. var ray = this.ray;
  60647. if (!this._attachedToMesh || !ray) {
  60648. return;
  60649. }
  60650. if (this._attachedToMesh._isDisposed) {
  60651. this.detachFromMesh();
  60652. return;
  60653. }
  60654. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60655. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60656. };
  60657. RayHelper.prototype.dispose = function () {
  60658. this.hide();
  60659. this.detachFromMesh();
  60660. this.ray = null;
  60661. };
  60662. return RayHelper;
  60663. }());
  60664. BABYLON.RayHelper = RayHelper;
  60665. })(BABYLON || (BABYLON = {}));
  60666. //# sourceMappingURL=babylon.rayHelper.js.map
  60667. var BABYLON;
  60668. (function (BABYLON) {
  60669. // load the inspector using require, if not present in the global namespace.
  60670. var DebugLayer = /** @class */ (function () {
  60671. function DebugLayer(scene) {
  60672. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60673. this.onPropertyChangedObservable = new BABYLON.Observable();
  60674. this._scene = scene;
  60675. }
  60676. /** Creates the inspector window. */
  60677. DebugLayer.prototype._createInspector = function (config) {
  60678. if (config === void 0) { config = {}; }
  60679. var popup = config.popup || false;
  60680. var initialTab = config.initialTab || 0;
  60681. var parentElement = config.parentElement || null;
  60682. if (!this._inspector) {
  60683. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60684. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60685. } // else nothing to do as instance is already created
  60686. };
  60687. DebugLayer.prototype.isVisible = function () {
  60688. if (!this._inspector) {
  60689. return false;
  60690. }
  60691. return true;
  60692. };
  60693. DebugLayer.prototype.hide = function () {
  60694. if (this._inspector) {
  60695. try {
  60696. this._inspector.dispose();
  60697. }
  60698. catch (e) {
  60699. // If the inspector has been removed directly from the inspector tool
  60700. }
  60701. this.onPropertyChangedObservable.clear();
  60702. this._inspector = null;
  60703. }
  60704. };
  60705. /**
  60706. *
  60707. * Launch the debugLayer.
  60708. *
  60709. * initialTab:
  60710. * | Value | Tab Name |
  60711. * | --- | --- |
  60712. * | 0 | Scene |
  60713. * | 1 | Console |
  60714. * | 2 | Stats |
  60715. * | 3 | Textures |
  60716. * | 4 | Mesh |
  60717. * | 5 | Light |
  60718. * | 6 | Material |
  60719. * | 7 | GLTF |
  60720. * | 8 | GUI |
  60721. * | 9 | Physics |
  60722. * | 10 | Camera |
  60723. * | 11 | Audio |
  60724. *
  60725. */
  60726. DebugLayer.prototype.show = function (config) {
  60727. if (config === void 0) { config = {}; }
  60728. if (typeof this.BJSINSPECTOR == 'undefined') {
  60729. // Load inspector and add it to the DOM
  60730. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60731. }
  60732. else {
  60733. // Otherwise creates the inspector
  60734. this._createInspector(config);
  60735. }
  60736. };
  60737. /**
  60738. * Gets the active tab
  60739. * @return the index of the active tab or -1 if the inspector is hidden
  60740. */
  60741. DebugLayer.prototype.getActiveTab = function () {
  60742. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60743. };
  60744. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60745. return DebugLayer;
  60746. }());
  60747. BABYLON.DebugLayer = DebugLayer;
  60748. })(BABYLON || (BABYLON = {}));
  60749. //# sourceMappingURL=babylon.debugLayer.js.map
  60750. var BABYLON;
  60751. (function (BABYLON) {
  60752. var Debug;
  60753. (function (Debug) {
  60754. /**
  60755. * Used to show the physics impostor around the specific mesh
  60756. */
  60757. var PhysicsViewer = /** @class */ (function () {
  60758. /**
  60759. * Creates a new PhysicsViewer
  60760. * @param scene defines the hosting scene
  60761. */
  60762. function PhysicsViewer(scene) {
  60763. /** @hidden */
  60764. this._impostors = [];
  60765. /** @hidden */
  60766. this._meshes = [];
  60767. /** @hidden */
  60768. this._numMeshes = 0;
  60769. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60770. var physicEngine = this._scene.getPhysicsEngine();
  60771. if (physicEngine) {
  60772. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60773. }
  60774. }
  60775. /** @hidden */
  60776. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60777. var plugin = this._physicsEnginePlugin;
  60778. for (var i = 0; i < this._numMeshes; i++) {
  60779. var impostor = this._impostors[i];
  60780. if (!impostor) {
  60781. continue;
  60782. }
  60783. if (impostor.isDisposed) {
  60784. this.hideImpostor(this._impostors[i--]);
  60785. }
  60786. else {
  60787. var mesh = this._meshes[i];
  60788. if (mesh && plugin) {
  60789. plugin.syncMeshWithImpostor(mesh, impostor);
  60790. }
  60791. }
  60792. }
  60793. };
  60794. /**
  60795. * Renders a specified physic impostor
  60796. * @param impostor defines the impostor to render
  60797. */
  60798. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60799. if (!this._scene) {
  60800. return;
  60801. }
  60802. for (var i = 0; i < this._numMeshes; i++) {
  60803. if (this._impostors[i] == impostor) {
  60804. return;
  60805. }
  60806. }
  60807. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60808. if (debugMesh) {
  60809. this._impostors[this._numMeshes] = impostor;
  60810. this._meshes[this._numMeshes] = debugMesh;
  60811. if (this._numMeshes === 0) {
  60812. this._renderFunction = this._updateDebugMeshes.bind(this);
  60813. this._scene.registerBeforeRender(this._renderFunction);
  60814. }
  60815. this._numMeshes++;
  60816. }
  60817. };
  60818. /**
  60819. * Hides a specified physic impostor
  60820. * @param impostor defines the impostor to hide
  60821. */
  60822. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60823. if (!impostor || !this._scene) {
  60824. return;
  60825. }
  60826. var removed = false;
  60827. for (var i = 0; i < this._numMeshes; i++) {
  60828. if (this._impostors[i] == impostor) {
  60829. var mesh = this._meshes[i];
  60830. if (!mesh) {
  60831. continue;
  60832. }
  60833. this._scene.removeMesh(mesh);
  60834. mesh.dispose();
  60835. this._numMeshes--;
  60836. if (this._numMeshes > 0) {
  60837. this._meshes[i] = this._meshes[this._numMeshes];
  60838. this._impostors[i] = this._impostors[this._numMeshes];
  60839. this._meshes[this._numMeshes] = null;
  60840. this._impostors[this._numMeshes] = null;
  60841. }
  60842. else {
  60843. this._meshes[0] = null;
  60844. this._impostors[0] = null;
  60845. }
  60846. removed = true;
  60847. break;
  60848. }
  60849. }
  60850. if (removed && this._numMeshes === 0) {
  60851. this._scene.unregisterBeforeRender(this._renderFunction);
  60852. }
  60853. };
  60854. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60855. if (!this._debugMaterial) {
  60856. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60857. this._debugMaterial.wireframe = true;
  60858. }
  60859. return this._debugMaterial;
  60860. };
  60861. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60862. if (!this._debugBoxMesh) {
  60863. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60864. this._debugBoxMesh.renderingGroupId = 1;
  60865. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60866. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60867. scene.removeMesh(this._debugBoxMesh);
  60868. }
  60869. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60870. };
  60871. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60872. if (!this._debugSphereMesh) {
  60873. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60874. this._debugSphereMesh.renderingGroupId = 1;
  60875. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60876. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60877. scene.removeMesh(this._debugSphereMesh);
  60878. }
  60879. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60880. };
  60881. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60882. var mesh = null;
  60883. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60884. mesh = this._getDebugBoxMesh(scene);
  60885. impostor.getBoxSizeToRef(mesh.scaling);
  60886. }
  60887. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60888. mesh = this._getDebugSphereMesh(scene);
  60889. var radius = impostor.getRadius();
  60890. mesh.scaling.x = radius * 2;
  60891. mesh.scaling.y = radius * 2;
  60892. mesh.scaling.z = radius * 2;
  60893. }
  60894. return mesh;
  60895. };
  60896. /** Releases all resources */
  60897. PhysicsViewer.prototype.dispose = function () {
  60898. for (var i = 0; i < this._numMeshes; i++) {
  60899. this.hideImpostor(this._impostors[i]);
  60900. }
  60901. if (this._debugBoxMesh) {
  60902. this._debugBoxMesh.dispose();
  60903. }
  60904. if (this._debugSphereMesh) {
  60905. this._debugSphereMesh.dispose();
  60906. }
  60907. if (this._debugMaterial) {
  60908. this._debugMaterial.dispose();
  60909. }
  60910. this._impostors.length = 0;
  60911. this._scene = null;
  60912. this._physicsEnginePlugin = null;
  60913. };
  60914. return PhysicsViewer;
  60915. }());
  60916. Debug.PhysicsViewer = PhysicsViewer;
  60917. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60918. })(BABYLON || (BABYLON = {}));
  60919. //# sourceMappingURL=babylon.physicsViewer.js.map
  60920. var BABYLON;
  60921. (function (BABYLON) {
  60922. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60923. get: function () {
  60924. return this._forceShowBoundingBoxes || false;
  60925. },
  60926. set: function (value) {
  60927. this._forceShowBoundingBoxes = value;
  60928. // Lazyly creates a BB renderer if needed.
  60929. if (value) {
  60930. this.getBoundingBoxRenderer();
  60931. }
  60932. },
  60933. enumerable: true,
  60934. configurable: true
  60935. });
  60936. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60937. if (!this._boundingBoxRenderer) {
  60938. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60939. }
  60940. return this._boundingBoxRenderer;
  60941. };
  60942. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60943. get: function () {
  60944. return this._showBoundingBox || false;
  60945. },
  60946. set: function (value) {
  60947. this._showBoundingBox = value;
  60948. // Lazyly creates a BB renderer if needed.
  60949. if (value) {
  60950. this.getScene().getBoundingBoxRenderer();
  60951. }
  60952. },
  60953. enumerable: true,
  60954. configurable: true
  60955. });
  60956. var BoundingBoxRenderer = /** @class */ (function () {
  60957. function BoundingBoxRenderer(scene) {
  60958. /**
  60959. * The component name helpfull to identify the component in the list of scene components.
  60960. */
  60961. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60962. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60963. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60964. this.showBackLines = true;
  60965. this.renderList = new BABYLON.SmartArray(32);
  60966. this._vertexBuffers = {};
  60967. this.scene = scene;
  60968. scene._addComponent(this);
  60969. }
  60970. /**
  60971. * Registers the component in a given scene
  60972. */
  60973. BoundingBoxRenderer.prototype.register = function () {
  60974. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60975. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60976. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60977. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60978. };
  60979. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60980. if (mesh.showSubMeshesBoundingBox) {
  60981. var boundingInfo = subMesh.getBoundingInfo();
  60982. if (boundingInfo !== null && boundingInfo !== undefined) {
  60983. this.renderList.push(boundingInfo.boundingBox);
  60984. }
  60985. }
  60986. };
  60987. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60988. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60989. var boundingInfo = sourceMesh.getBoundingInfo();
  60990. this.renderList.push(boundingInfo.boundingBox);
  60991. }
  60992. };
  60993. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60994. if (this._colorShader) {
  60995. return;
  60996. }
  60997. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60998. attributes: [BABYLON.VertexBuffer.PositionKind],
  60999. uniforms: ["world", "viewProjection", "color"]
  61000. });
  61001. var engine = this.scene.getEngine();
  61002. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61003. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61004. this._createIndexBuffer();
  61005. };
  61006. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61007. var engine = this.scene.getEngine();
  61008. 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]);
  61009. };
  61010. /**
  61011. * Rebuilds the elements related to this component in case of
  61012. * context lost for instance.
  61013. */
  61014. BoundingBoxRenderer.prototype.rebuild = function () {
  61015. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61016. if (vb) {
  61017. vb._rebuild();
  61018. }
  61019. this._createIndexBuffer();
  61020. };
  61021. BoundingBoxRenderer.prototype.reset = function () {
  61022. this.renderList.reset();
  61023. };
  61024. BoundingBoxRenderer.prototype.render = function () {
  61025. if (this.renderList.length === 0) {
  61026. return;
  61027. }
  61028. this._prepareRessources();
  61029. if (!this._colorShader.isReady()) {
  61030. return;
  61031. }
  61032. var engine = this.scene.getEngine();
  61033. engine.setDepthWrite(false);
  61034. this._colorShader._preBind();
  61035. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61036. var boundingBox = this.renderList.data[boundingBoxIndex];
  61037. var min = boundingBox.minimum;
  61038. var max = boundingBox.maximum;
  61039. var diff = max.subtract(min);
  61040. var median = min.add(diff.scale(0.5));
  61041. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61042. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61043. .multiply(boundingBox.getWorldMatrix());
  61044. // VBOs
  61045. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61046. if (this.showBackLines) {
  61047. // Back
  61048. engine.setDepthFunctionToGreaterOrEqual();
  61049. this.scene.resetCachedMaterial();
  61050. this._colorShader.setColor4("color", this.backColor.toColor4());
  61051. this._colorShader.bind(worldMatrix);
  61052. // Draw order
  61053. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61054. }
  61055. // Front
  61056. engine.setDepthFunctionToLess();
  61057. this.scene.resetCachedMaterial();
  61058. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61059. this._colorShader.bind(worldMatrix);
  61060. // Draw order
  61061. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61062. }
  61063. this._colorShader.unbind();
  61064. engine.setDepthFunctionToLessOrEqual();
  61065. engine.setDepthWrite(true);
  61066. };
  61067. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61068. this._prepareRessources();
  61069. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61070. return;
  61071. }
  61072. var engine = this.scene.getEngine();
  61073. engine.setDepthWrite(false);
  61074. engine.setColorWrite(false);
  61075. this._colorShader._preBind();
  61076. var boundingBox = mesh._boundingInfo.boundingBox;
  61077. var min = boundingBox.minimum;
  61078. var max = boundingBox.maximum;
  61079. var diff = max.subtract(min);
  61080. var median = min.add(diff.scale(0.5));
  61081. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61082. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61083. .multiply(boundingBox.getWorldMatrix());
  61084. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61085. engine.setDepthFunctionToLess();
  61086. this.scene.resetCachedMaterial();
  61087. this._colorShader.bind(worldMatrix);
  61088. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61089. this._colorShader.unbind();
  61090. engine.setDepthFunctionToLessOrEqual();
  61091. engine.setDepthWrite(true);
  61092. engine.setColorWrite(true);
  61093. };
  61094. BoundingBoxRenderer.prototype.dispose = function () {
  61095. if (!this._colorShader) {
  61096. return;
  61097. }
  61098. this.renderList.dispose();
  61099. this._colorShader.dispose();
  61100. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61101. if (buffer) {
  61102. buffer.dispose();
  61103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61104. }
  61105. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61106. };
  61107. return BoundingBoxRenderer;
  61108. }());
  61109. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61110. })(BABYLON || (BABYLON = {}));
  61111. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61112. var BABYLON;
  61113. (function (BABYLON) {
  61114. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61115. return this._gl.createTransformFeedback();
  61116. };
  61117. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61118. this._gl.deleteTransformFeedback(value);
  61119. };
  61120. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61121. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61122. };
  61123. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61124. if (usePoints === void 0) { usePoints = true; }
  61125. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61126. };
  61127. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61128. this._gl.endTransformFeedback();
  61129. };
  61130. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61131. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61132. };
  61133. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61134. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61135. };
  61136. })(BABYLON || (BABYLON = {}));
  61137. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61138. var BABYLON;
  61139. (function (BABYLON) {
  61140. /**
  61141. * This represents a GPU particle system in Babylon
  61142. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61143. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61144. */
  61145. var GPUParticleSystem = /** @class */ (function (_super) {
  61146. __extends(GPUParticleSystem, _super);
  61147. /**
  61148. * Instantiates a GPU particle system.
  61149. * 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.
  61150. * @param name The name of the particle system
  61151. * @param options The options used to create the system
  61152. * @param scene The scene the particle system belongs to
  61153. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61154. */
  61155. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61156. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61157. var _this = _super.call(this, name) || this;
  61158. /**
  61159. * The layer mask we are rendering the particles through.
  61160. */
  61161. _this.layerMask = 0x0FFFFFFF;
  61162. _this._accumulatedCount = 0;
  61163. _this._targetIndex = 0;
  61164. _this._currentRenderId = -1;
  61165. _this._started = false;
  61166. _this._stopped = false;
  61167. _this._timeDelta = 0;
  61168. _this._attributesStrideSize = 21;
  61169. _this._actualFrame = 0;
  61170. _this._rawTextureWidth = 256;
  61171. /**
  61172. * An event triggered when the system is disposed.
  61173. */
  61174. _this.onDisposeObservable = new BABYLON.Observable();
  61175. /**
  61176. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61177. * to override the particles.
  61178. */
  61179. _this.forceDepthWrite = false;
  61180. _this._preWarmDone = false;
  61181. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61182. // Setup the default processing configuration to the scene.
  61183. _this._attachImageProcessingConfiguration(null);
  61184. _this._engine = _this._scene.getEngine();
  61185. if (!options.randomTextureSize) {
  61186. delete options.randomTextureSize;
  61187. }
  61188. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61189. var optionsAsNumber = options;
  61190. if (isFinite(optionsAsNumber)) {
  61191. fullOptions.capacity = optionsAsNumber;
  61192. }
  61193. _this._capacity = fullOptions.capacity;
  61194. _this._activeCount = fullOptions.capacity;
  61195. _this._currentActiveCount = 0;
  61196. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61197. _this._scene.particleSystems.push(_this);
  61198. _this._updateEffectOptions = {
  61199. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  61200. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61201. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61202. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61203. uniformBuffersNames: [],
  61204. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61205. defines: "",
  61206. fallbacks: null,
  61207. onCompiled: null,
  61208. onError: null,
  61209. indexParameters: null,
  61210. maxSimultaneousLights: 0,
  61211. transformFeedbackVaryings: []
  61212. };
  61213. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61214. // Random data
  61215. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61216. var d = [];
  61217. for (var i = 0; i < maxTextureSize; ++i) {
  61218. d.push(Math.random());
  61219. d.push(Math.random());
  61220. d.push(Math.random());
  61221. d.push(Math.random());
  61222. }
  61223. _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61224. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61225. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61226. d = [];
  61227. for (var i = 0; i < maxTextureSize; ++i) {
  61228. d.push(Math.random());
  61229. d.push(Math.random());
  61230. d.push(Math.random());
  61231. d.push(Math.random());
  61232. }
  61233. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  61234. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61235. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61236. _this._randomTextureSize = maxTextureSize;
  61237. return _this;
  61238. }
  61239. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61240. /**
  61241. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61242. */
  61243. get: function () {
  61244. if (!BABYLON.Engine.LastCreatedEngine) {
  61245. return false;
  61246. }
  61247. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61248. },
  61249. enumerable: true,
  61250. configurable: true
  61251. });
  61252. /**
  61253. * Gets the maximum number of particles active at the same time.
  61254. * @returns The max number of active particles.
  61255. */
  61256. GPUParticleSystem.prototype.getCapacity = function () {
  61257. return this._capacity;
  61258. };
  61259. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61260. /**
  61261. * Gets or set the number of active particles
  61262. */
  61263. get: function () {
  61264. return this._activeCount;
  61265. },
  61266. set: function (value) {
  61267. this._activeCount = Math.min(value, this._capacity);
  61268. },
  61269. enumerable: true,
  61270. configurable: true
  61271. });
  61272. /**
  61273. * Is this system ready to be used/rendered
  61274. * @return true if the system is ready
  61275. */
  61276. GPUParticleSystem.prototype.isReady = function () {
  61277. if (!this._updateEffect) {
  61278. this._recreateUpdateEffect();
  61279. this._recreateRenderEffect();
  61280. return false;
  61281. }
  61282. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61283. return false;
  61284. }
  61285. return true;
  61286. };
  61287. /**
  61288. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61289. * @returns True if it has been started, otherwise false.
  61290. */
  61291. GPUParticleSystem.prototype.isStarted = function () {
  61292. return this._started;
  61293. };
  61294. /**
  61295. * Starts the particle system and begins to emit
  61296. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61297. */
  61298. GPUParticleSystem.prototype.start = function (delay) {
  61299. var _this = this;
  61300. if (delay === void 0) { delay = 0; }
  61301. if (delay) {
  61302. setTimeout(function () {
  61303. _this.start(0);
  61304. }, delay);
  61305. return;
  61306. }
  61307. this._started = true;
  61308. this._stopped = false;
  61309. this._preWarmDone = false;
  61310. };
  61311. /**
  61312. * Stops the particle system.
  61313. */
  61314. GPUParticleSystem.prototype.stop = function () {
  61315. this._stopped = true;
  61316. };
  61317. /**
  61318. * Remove all active particles
  61319. */
  61320. GPUParticleSystem.prototype.reset = function () {
  61321. this._releaseBuffers();
  61322. this._releaseVAOs();
  61323. this._currentActiveCount = 0;
  61324. this._targetIndex = 0;
  61325. };
  61326. /**
  61327. * Returns the string "GPUParticleSystem"
  61328. * @returns a string containing the class name
  61329. */
  61330. GPUParticleSystem.prototype.getClassName = function () {
  61331. return "GPUParticleSystem";
  61332. };
  61333. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  61334. if (!gradients) {
  61335. return this;
  61336. }
  61337. var index = 0;
  61338. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  61339. var valueGradient = gradients_1[_i];
  61340. if (valueGradient.gradient === gradient) {
  61341. gradients.splice(index, 1);
  61342. break;
  61343. }
  61344. index++;
  61345. }
  61346. if (texture) {
  61347. texture.dispose();
  61348. }
  61349. this._releaseBuffers();
  61350. return this;
  61351. };
  61352. /**
  61353. * Adds a new color gradient
  61354. * @param gradient defines the gradient to use (between 0 and 1)
  61355. * @param color defines the color to affect to the specified gradient
  61356. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61357. * @returns the current particle system
  61358. */
  61359. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61360. if (!this._colorGradients) {
  61361. this._colorGradients = [];
  61362. }
  61363. var colorGradient = new BABYLON.ColorGradient();
  61364. colorGradient.gradient = gradient;
  61365. colorGradient.color1 = color1;
  61366. this._colorGradients.push(colorGradient);
  61367. this._colorGradients.sort(function (a, b) {
  61368. if (a.gradient < b.gradient) {
  61369. return -1;
  61370. }
  61371. else if (a.gradient > b.gradient) {
  61372. return 1;
  61373. }
  61374. return 0;
  61375. });
  61376. if (this._colorGradientsTexture) {
  61377. this._colorGradientsTexture.dispose();
  61378. this._colorGradientsTexture = null;
  61379. }
  61380. this._releaseBuffers();
  61381. return this;
  61382. };
  61383. /**
  61384. * Remove a specific color gradient
  61385. * @param gradient defines the gradient to remove
  61386. * @returns the current particle system
  61387. */
  61388. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61389. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  61390. this._colorGradientsTexture = null;
  61391. return this;
  61392. };
  61393. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61394. var valueGradient = new BABYLON.FactorGradient();
  61395. valueGradient.gradient = gradient;
  61396. valueGradient.factor1 = factor;
  61397. factorGradients.push(valueGradient);
  61398. factorGradients.sort(function (a, b) {
  61399. if (a.gradient < b.gradient) {
  61400. return -1;
  61401. }
  61402. else if (a.gradient > b.gradient) {
  61403. return 1;
  61404. }
  61405. return 0;
  61406. });
  61407. this._releaseBuffers();
  61408. };
  61409. /**
  61410. * Adds a new size gradient
  61411. * @param gradient defines the gradient to use (between 0 and 1)
  61412. * @param factor defines the size factor to affect to the specified gradient
  61413. * @returns the current particle system
  61414. */
  61415. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61416. if (!this._sizeGradients) {
  61417. this._sizeGradients = [];
  61418. }
  61419. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61420. if (this._sizeGradientsTexture) {
  61421. this._sizeGradientsTexture.dispose();
  61422. this._sizeGradientsTexture = null;
  61423. }
  61424. this._releaseBuffers();
  61425. return this;
  61426. };
  61427. /**
  61428. * Remove a specific size gradient
  61429. * @param gradient defines the gradient to remove
  61430. * @returns the current particle system
  61431. */
  61432. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61433. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61434. this._sizeGradientsTexture = null;
  61435. return this;
  61436. };
  61437. /**
  61438. * Adds a new angular speed gradient
  61439. * @param gradient defines the gradient to use (between 0 and 1)
  61440. * @param factor defines the angular speed to affect to the specified gradient
  61441. * @returns the current particle system
  61442. */
  61443. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61444. if (!this._angularSpeedGradients) {
  61445. this._angularSpeedGradients = [];
  61446. }
  61447. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61448. if (this._angularSpeedGradientsTexture) {
  61449. this._angularSpeedGradientsTexture.dispose();
  61450. this._angularSpeedGradientsTexture = null;
  61451. }
  61452. this._releaseBuffers();
  61453. return this;
  61454. };
  61455. /**
  61456. * Remove a specific angular speed gradient
  61457. * @param gradient defines the gradient to remove
  61458. * @returns the current particle system
  61459. */
  61460. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61461. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61462. this._angularSpeedGradientsTexture = null;
  61463. return this;
  61464. };
  61465. /**
  61466. * Adds a new velocity gradient
  61467. * @param gradient defines the gradient to use (between 0 and 1)
  61468. * @param factor defines the velocity to affect to the specified gradient
  61469. * @returns the current particle system
  61470. */
  61471. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61472. if (!this._velocityGradients) {
  61473. this._velocityGradients = [];
  61474. }
  61475. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61476. if (this._velocityGradientsTexture) {
  61477. this._velocityGradientsTexture.dispose();
  61478. this._velocityGradientsTexture = null;
  61479. }
  61480. this._releaseBuffers();
  61481. return this;
  61482. };
  61483. /**
  61484. * Remove a specific velocity gradient
  61485. * @param gradient defines the gradient to remove
  61486. * @returns the current particle system
  61487. */
  61488. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61489. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61490. this._velocityGradientsTexture = null;
  61491. return this;
  61492. };
  61493. /**
  61494. * Adds a new limit velocity gradient
  61495. * @param gradient defines the gradient to use (between 0 and 1)
  61496. * @param factor defines the limit velocity value to affect to the specified gradient
  61497. * @returns the current particle system
  61498. */
  61499. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61500. if (!this._limitVelocityGradients) {
  61501. this._limitVelocityGradients = [];
  61502. }
  61503. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61504. if (this._limitVelocityGradientsTexture) {
  61505. this._limitVelocityGradientsTexture.dispose();
  61506. this._limitVelocityGradientsTexture = null;
  61507. }
  61508. this._releaseBuffers();
  61509. return this;
  61510. };
  61511. /**
  61512. * Remove a specific limit velocity gradient
  61513. * @param gradient defines the gradient to remove
  61514. * @returns the current particle system
  61515. */
  61516. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61517. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61518. this._limitVelocityGradientsTexture = null;
  61519. return this;
  61520. };
  61521. /**
  61522. * Adds a new drag gradient
  61523. * @param gradient defines the gradient to use (between 0 and 1)
  61524. * @param factor defines the drag value to affect to the specified gradient
  61525. * @returns the current particle system
  61526. */
  61527. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61528. if (!this._dragGradients) {
  61529. this._dragGradients = [];
  61530. }
  61531. this._addFactorGradient(this._dragGradients, gradient, factor);
  61532. if (this._dragGradientsTexture) {
  61533. this._dragGradientsTexture.dispose();
  61534. this._dragGradientsTexture = null;
  61535. }
  61536. this._releaseBuffers();
  61537. return this;
  61538. };
  61539. /**
  61540. * Remove a specific drag gradient
  61541. * @param gradient defines the gradient to remove
  61542. * @returns the current particle system
  61543. */
  61544. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61545. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61546. this._dragGradientsTexture = null;
  61547. return this;
  61548. };
  61549. /**
  61550. * Not supported by GPUParticleSystem
  61551. * @param gradient defines the gradient to use (between 0 and 1)
  61552. * @param factor defines the emit rate value to affect to the specified gradient
  61553. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61554. * @returns the current particle system
  61555. */
  61556. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61557. // Do nothing as emit rate is not supported by GPUParticleSystem
  61558. return this;
  61559. };
  61560. /**
  61561. * Not supported by GPUParticleSystem
  61562. * @param gradient defines the gradient to remove
  61563. * @returns the current particle system
  61564. */
  61565. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61566. // Do nothing as emit rate is not supported by GPUParticleSystem
  61567. return this;
  61568. };
  61569. /**
  61570. * Not supported by GPUParticleSystem
  61571. * @param gradient defines the gradient to use (between 0 and 1)
  61572. * @param factor defines the start size value to affect to the specified gradient
  61573. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61574. * @returns the current particle system
  61575. */
  61576. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61577. // Do nothing as start size is not supported by GPUParticleSystem
  61578. return this;
  61579. };
  61580. /**
  61581. * Not supported by GPUParticleSystem
  61582. * @param gradient defines the gradient to remove
  61583. * @returns the current particle system
  61584. */
  61585. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61586. // Do nothing as start size is not supported by GPUParticleSystem
  61587. return this;
  61588. };
  61589. GPUParticleSystem.prototype._reset = function () {
  61590. this._releaseBuffers();
  61591. };
  61592. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61593. var updateVertexBuffers = {};
  61594. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61595. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61596. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61597. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61598. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61599. var offset = 12;
  61600. if (!this._colorGradientsTexture) {
  61601. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61602. offset += 4;
  61603. }
  61604. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61605. offset += 3;
  61606. if (!this._isBillboardBased) {
  61607. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61608. offset += 3;
  61609. }
  61610. if (this._angularSpeedGradientsTexture) {
  61611. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61612. offset += 1;
  61613. }
  61614. else {
  61615. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61616. offset += 2;
  61617. }
  61618. if (this._isAnimationSheetEnabled) {
  61619. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61620. offset += 1;
  61621. if (this.spriteRandomStartCell) {
  61622. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  61623. offset += 1;
  61624. }
  61625. }
  61626. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61627. this._engine.bindArrayBuffer(null);
  61628. return vao;
  61629. };
  61630. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61631. var renderVertexBuffers = {};
  61632. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61633. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61634. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61635. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61636. var offset = 12;
  61637. if (!this._colorGradientsTexture) {
  61638. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61639. offset += 4;
  61640. }
  61641. offset += 3; // Direction
  61642. if (!this._isBillboardBased) {
  61643. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61644. offset += 3;
  61645. }
  61646. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61647. if (this._angularSpeedGradientsTexture) {
  61648. offset++;
  61649. }
  61650. else {
  61651. offset += 2;
  61652. }
  61653. if (this._isAnimationSheetEnabled) {
  61654. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61655. offset += 1;
  61656. if (this.spriteRandomStartCell) {
  61657. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  61658. offset += 1;
  61659. }
  61660. }
  61661. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61662. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61663. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61664. this._engine.bindArrayBuffer(null);
  61665. return vao;
  61666. };
  61667. GPUParticleSystem.prototype._initialize = function (force) {
  61668. if (force === void 0) { force = false; }
  61669. if (this._buffer0 && !force) {
  61670. return;
  61671. }
  61672. var engine = this._scene.getEngine();
  61673. var data = new Array();
  61674. if (!this.isBillboardBased) {
  61675. this._attributesStrideSize += 3;
  61676. }
  61677. if (this._colorGradientsTexture) {
  61678. this._attributesStrideSize -= 4;
  61679. }
  61680. if (this._angularSpeedGradientsTexture) {
  61681. this._attributesStrideSize -= 1;
  61682. }
  61683. if (this._isAnimationSheetEnabled) {
  61684. this._attributesStrideSize += 1;
  61685. if (this.spriteRandomStartCell) {
  61686. this._attributesStrideSize += 1;
  61687. }
  61688. }
  61689. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61690. // position
  61691. data.push(0.0);
  61692. data.push(0.0);
  61693. data.push(0.0);
  61694. // Age and life
  61695. data.push(0.0); // create the particle as a dead one to create a new one at start
  61696. data.push(0.0);
  61697. // Seed
  61698. data.push(Math.random());
  61699. data.push(Math.random());
  61700. data.push(Math.random());
  61701. data.push(Math.random());
  61702. // Size
  61703. data.push(0.0);
  61704. data.push(0.0);
  61705. data.push(0.0);
  61706. if (!this._colorGradientsTexture) {
  61707. // color
  61708. data.push(0.0);
  61709. data.push(0.0);
  61710. data.push(0.0);
  61711. data.push(0.0);
  61712. }
  61713. // direction
  61714. data.push(0.0);
  61715. data.push(0.0);
  61716. data.push(0.0);
  61717. if (!this.isBillboardBased) {
  61718. // initialDirection
  61719. data.push(0.0);
  61720. data.push(0.0);
  61721. data.push(0.0);
  61722. }
  61723. // angle
  61724. data.push(0.0);
  61725. if (!this._angularSpeedGradientsTexture) {
  61726. data.push(0.0);
  61727. }
  61728. if (this._isAnimationSheetEnabled) {
  61729. data.push(0.0);
  61730. if (this.spriteRandomStartCell) {
  61731. data.push(0.0);
  61732. }
  61733. }
  61734. }
  61735. // Sprite data
  61736. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61737. -0.5, 0.5, 0, 1,
  61738. -0.5, -0.5, 0, 0,
  61739. 0.5, -0.5, 1, 0]);
  61740. // Buffers
  61741. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61742. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61743. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61744. // Update VAO
  61745. this._updateVAO = [];
  61746. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61747. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61748. // Render VAO
  61749. this._renderVAO = [];
  61750. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61751. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61752. // Links
  61753. this._sourceBuffer = this._buffer0;
  61754. this._targetBuffer = this._buffer1;
  61755. };
  61756. /** @hidden */
  61757. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61758. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61759. if (this._isBillboardBased) {
  61760. defines += "\n#define BILLBOARD";
  61761. }
  61762. if (this._colorGradientsTexture) {
  61763. defines += "\n#define COLORGRADIENTS";
  61764. }
  61765. if (this._sizeGradientsTexture) {
  61766. defines += "\n#define SIZEGRADIENTS";
  61767. }
  61768. if (this._angularSpeedGradientsTexture) {
  61769. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61770. }
  61771. if (this._velocityGradientsTexture) {
  61772. defines += "\n#define VELOCITYGRADIENTS";
  61773. }
  61774. if (this._limitVelocityGradientsTexture) {
  61775. defines += "\n#define LIMITVELOCITYGRADIENTS";
  61776. }
  61777. if (this._dragGradientsTexture) {
  61778. defines += "\n#define DRAGGRADIENTS";
  61779. }
  61780. if (this.isAnimationSheetEnabled) {
  61781. defines += "\n#define ANIMATESHEET";
  61782. if (this.spriteRandomStartCell) {
  61783. defines += "\n#define ANIMATESHEETRANDOMSTART";
  61784. }
  61785. }
  61786. if (this.noiseTexture) {
  61787. defines += "\n#define NOISE";
  61788. }
  61789. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61790. return;
  61791. }
  61792. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61793. if (!this._colorGradientsTexture) {
  61794. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61795. }
  61796. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61797. if (!this._isBillboardBased) {
  61798. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61799. }
  61800. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61801. if (this.isAnimationSheetEnabled) {
  61802. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61803. if (this.spriteRandomStartCell) {
  61804. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  61805. }
  61806. }
  61807. this._updateEffectOptions.defines = defines;
  61808. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61809. };
  61810. /** @hidden */
  61811. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61812. var defines = "";
  61813. if (this._scene.clipPlane) {
  61814. defines = "\n#define CLIPPLANE";
  61815. }
  61816. if (this._scene.clipPlane2) {
  61817. defines = "\n#define CLIPPLANE2";
  61818. }
  61819. if (this._scene.clipPlane3) {
  61820. defines = "\n#define CLIPPLANE3";
  61821. }
  61822. if (this._scene.clipPlane4) {
  61823. defines = "\n#define CLIPPLANE4";
  61824. }
  61825. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  61826. defines = "\n#define BLENDMULTIPLYMODE";
  61827. }
  61828. if (this._isBillboardBased) {
  61829. defines += "\n#define BILLBOARD";
  61830. switch (this.billboardMode) {
  61831. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61832. defines += "\n#define BILLBOARDY";
  61833. break;
  61834. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61835. default:
  61836. break;
  61837. }
  61838. }
  61839. if (this._colorGradientsTexture) {
  61840. defines += "\n#define COLORGRADIENTS";
  61841. }
  61842. if (this.isAnimationSheetEnabled) {
  61843. defines += "\n#define ANIMATESHEET";
  61844. }
  61845. if (this._imageProcessingConfiguration) {
  61846. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61847. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61848. }
  61849. if (this._renderEffect && this._renderEffect.defines === defines) {
  61850. return;
  61851. }
  61852. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61853. var samplers = ["textureSampler", "colorGradientSampler"];
  61854. if (BABYLON.ImageProcessingConfiguration) {
  61855. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61856. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61857. }
  61858. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61859. };
  61860. /**
  61861. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61862. * @param preWarm defines if we are in the pre-warmimg phase
  61863. */
  61864. GPUParticleSystem.prototype.animate = function (preWarm) {
  61865. if (preWarm === void 0) { preWarm = false; }
  61866. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61867. this._actualFrame += this._timeDelta;
  61868. if (!this._stopped) {
  61869. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61870. this.stop();
  61871. }
  61872. }
  61873. };
  61874. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61875. var texture = this[textureName];
  61876. if (!factorGradients || !factorGradients.length || texture) {
  61877. return;
  61878. }
  61879. var data = new Float32Array(this._rawTextureWidth);
  61880. for (var x = 0; x < this._rawTextureWidth; x++) {
  61881. var ratio = x / this._rawTextureWidth;
  61882. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61883. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61884. });
  61885. }
  61886. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61887. };
  61888. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61889. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61890. };
  61891. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61892. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61893. };
  61894. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61895. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61896. };
  61897. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  61898. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  61899. };
  61900. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  61901. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  61902. };
  61903. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61904. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61905. return;
  61906. }
  61907. var data = new Uint8Array(this._rawTextureWidth * 4);
  61908. var tmpColor = BABYLON.Tmp.Color4[0];
  61909. for (var x = 0; x < this._rawTextureWidth; x++) {
  61910. var ratio = x / this._rawTextureWidth;
  61911. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61912. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61913. data[x * 4] = tmpColor.r * 255;
  61914. data[x * 4 + 1] = tmpColor.g * 255;
  61915. data[x * 4 + 2] = tmpColor.b * 255;
  61916. data[x * 4 + 3] = tmpColor.a * 255;
  61917. });
  61918. }
  61919. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61920. };
  61921. /**
  61922. * Renders the particle system in its current state
  61923. * @param preWarm defines if the system should only update the particles but not render them
  61924. * @returns the current number of particles
  61925. */
  61926. GPUParticleSystem.prototype.render = function (preWarm) {
  61927. if (preWarm === void 0) { preWarm = false; }
  61928. if (!this._started) {
  61929. return 0;
  61930. }
  61931. this._createColorGradientTexture();
  61932. this._createSizeGradientTexture();
  61933. this._createAngularSpeedGradientTexture();
  61934. this._createVelocityGradientTexture();
  61935. this._createLimitVelocityGradientTexture();
  61936. this._createDragGradientTexture();
  61937. this._recreateUpdateEffect();
  61938. this._recreateRenderEffect();
  61939. if (!this.isReady()) {
  61940. return 0;
  61941. }
  61942. if (!preWarm) {
  61943. if (!this._preWarmDone && this.preWarmCycles) {
  61944. for (var index = 0; index < this.preWarmCycles; index++) {
  61945. this.animate(true);
  61946. this.render(true);
  61947. }
  61948. this._preWarmDone = true;
  61949. }
  61950. if (this._currentRenderId === this._scene.getRenderId()) {
  61951. return 0;
  61952. }
  61953. this._currentRenderId = this._scene.getRenderId();
  61954. }
  61955. // Get everything ready to render
  61956. this._initialize();
  61957. this._accumulatedCount += this.emitRate * this._timeDelta;
  61958. if (this._accumulatedCount > 1) {
  61959. var intPart = this._accumulatedCount | 0;
  61960. this._accumulatedCount -= intPart;
  61961. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61962. }
  61963. if (!this._currentActiveCount) {
  61964. return 0;
  61965. }
  61966. // Enable update effect
  61967. this._engine.enableEffect(this._updateEffect);
  61968. this._engine.setState(false);
  61969. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61970. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61971. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61972. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61973. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61974. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61975. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61976. if (!this._colorGradientsTexture) {
  61977. this._updateEffect.setDirectColor4("color1", this.color1);
  61978. this._updateEffect.setDirectColor4("color2", this.color2);
  61979. }
  61980. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61981. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61982. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61983. this._updateEffect.setVector3("gravity", this.gravity);
  61984. if (this._sizeGradientsTexture) {
  61985. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61986. }
  61987. if (this._angularSpeedGradientsTexture) {
  61988. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61989. }
  61990. if (this._velocityGradientsTexture) {
  61991. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61992. }
  61993. if (this._limitVelocityGradientsTexture) {
  61994. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  61995. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  61996. }
  61997. if (this._dragGradientsTexture) {
  61998. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  61999. }
  62000. if (this.particleEmitterType) {
  62001. this.particleEmitterType.applyToShader(this._updateEffect);
  62002. }
  62003. if (this._isAnimationSheetEnabled) {
  62004. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62005. }
  62006. if (this.noiseTexture) {
  62007. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62008. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62009. }
  62010. var emitterWM;
  62011. if (this.emitter.position) {
  62012. var emitterMesh = this.emitter;
  62013. emitterWM = emitterMesh.getWorldMatrix();
  62014. }
  62015. else {
  62016. var emitterPosition = this.emitter;
  62017. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62018. }
  62019. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62020. // Bind source VAO
  62021. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62022. // Update
  62023. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62024. this._engine.setRasterizerState(false);
  62025. this._engine.beginTransformFeedback(true);
  62026. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62027. this._engine.endTransformFeedback();
  62028. this._engine.setRasterizerState(true);
  62029. this._engine.bindTransformFeedbackBuffer(null);
  62030. if (!preWarm) {
  62031. // Enable render effect
  62032. this._engine.enableEffect(this._renderEffect);
  62033. var viewMatrix = this._scene.getViewMatrix();
  62034. this._renderEffect.setMatrix("view", viewMatrix);
  62035. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62036. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62037. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62038. if (this._colorGradientsTexture) {
  62039. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62040. }
  62041. else {
  62042. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62043. }
  62044. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62045. var baseSize = this.particleTexture.getBaseSize();
  62046. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62047. }
  62048. if (this._isBillboardBased) {
  62049. var camera = this._scene.activeCamera;
  62050. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62051. }
  62052. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62053. var invView = viewMatrix.clone();
  62054. invView.invert();
  62055. this._renderEffect.setMatrix("invView", invView);
  62056. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62057. }
  62058. // image processing
  62059. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62060. this._imageProcessingConfiguration.bind(this._renderEffect);
  62061. }
  62062. // Draw order
  62063. switch (this.blendMode) {
  62064. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62065. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62066. break;
  62067. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62068. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62069. break;
  62070. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62071. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62072. break;
  62073. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62074. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62075. break;
  62076. }
  62077. if (this.forceDepthWrite) {
  62078. this._engine.setDepthWrite(true);
  62079. }
  62080. // Bind source VAO
  62081. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62082. // Render
  62083. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62084. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62085. }
  62086. // Switch VAOs
  62087. this._targetIndex++;
  62088. if (this._targetIndex === 2) {
  62089. this._targetIndex = 0;
  62090. }
  62091. // Switch buffers
  62092. var tmpBuffer = this._sourceBuffer;
  62093. this._sourceBuffer = this._targetBuffer;
  62094. this._targetBuffer = tmpBuffer;
  62095. return this._currentActiveCount;
  62096. };
  62097. /**
  62098. * Rebuilds the particle system
  62099. */
  62100. GPUParticleSystem.prototype.rebuild = function () {
  62101. this._initialize(true);
  62102. };
  62103. GPUParticleSystem.prototype._releaseBuffers = function () {
  62104. if (this._buffer0) {
  62105. this._buffer0.dispose();
  62106. this._buffer0 = null;
  62107. }
  62108. if (this._buffer1) {
  62109. this._buffer1.dispose();
  62110. this._buffer1 = null;
  62111. }
  62112. if (this._spriteBuffer) {
  62113. this._spriteBuffer.dispose();
  62114. this._spriteBuffer = null;
  62115. }
  62116. };
  62117. GPUParticleSystem.prototype._releaseVAOs = function () {
  62118. if (!this._updateVAO) {
  62119. return;
  62120. }
  62121. for (var index = 0; index < this._updateVAO.length; index++) {
  62122. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62123. }
  62124. this._updateVAO = [];
  62125. for (var index = 0; index < this._renderVAO.length; index++) {
  62126. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62127. }
  62128. this._renderVAO = [];
  62129. };
  62130. /**
  62131. * Disposes the particle system and free the associated resources
  62132. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62133. */
  62134. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62135. if (disposeTexture === void 0) { disposeTexture = true; }
  62136. var index = this._scene.particleSystems.indexOf(this);
  62137. if (index > -1) {
  62138. this._scene.particleSystems.splice(index, 1);
  62139. }
  62140. this._releaseBuffers();
  62141. this._releaseVAOs();
  62142. if (this._colorGradientsTexture) {
  62143. this._colorGradientsTexture.dispose();
  62144. this._colorGradientsTexture = null;
  62145. }
  62146. if (this._sizeGradientsTexture) {
  62147. this._sizeGradientsTexture.dispose();
  62148. this._sizeGradientsTexture = null;
  62149. }
  62150. if (this._angularSpeedGradientsTexture) {
  62151. this._angularSpeedGradientsTexture.dispose();
  62152. this._angularSpeedGradientsTexture = null;
  62153. }
  62154. if (this._velocityGradientsTexture) {
  62155. this._velocityGradientsTexture.dispose();
  62156. this._velocityGradientsTexture = null;
  62157. }
  62158. if (this._limitVelocityGradientsTexture) {
  62159. this._limitVelocityGradientsTexture.dispose();
  62160. this._limitVelocityGradientsTexture = null;
  62161. }
  62162. if (this._dragGradientsTexture) {
  62163. this._dragGradientsTexture.dispose();
  62164. this._dragGradientsTexture = null;
  62165. }
  62166. if (this._randomTexture) {
  62167. this._randomTexture.dispose();
  62168. this._randomTexture = null;
  62169. }
  62170. if (this._randomTexture2) {
  62171. this._randomTexture2.dispose();
  62172. this._randomTexture2 = null;
  62173. }
  62174. if (disposeTexture && this.particleTexture) {
  62175. this.particleTexture.dispose();
  62176. this.particleTexture = null;
  62177. }
  62178. if (disposeTexture && this.noiseTexture) {
  62179. this.noiseTexture.dispose();
  62180. this.noiseTexture = null;
  62181. }
  62182. // Callback
  62183. this.onDisposeObservable.notifyObservers(this);
  62184. this.onDisposeObservable.clear();
  62185. };
  62186. /**
  62187. * Clones the particle system.
  62188. * @param name The name of the cloned object
  62189. * @param newEmitter The new emitter to use
  62190. * @returns the cloned particle system
  62191. */
  62192. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62193. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62194. BABYLON.Tools.DeepCopy(this, result);
  62195. if (newEmitter === undefined) {
  62196. newEmitter = this.emitter;
  62197. }
  62198. result.emitter = newEmitter;
  62199. if (this.particleTexture) {
  62200. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62201. }
  62202. return result;
  62203. };
  62204. /**
  62205. * Serializes the particle system to a JSON object.
  62206. * @returns the JSON object
  62207. */
  62208. GPUParticleSystem.prototype.serialize = function () {
  62209. var serializationObject = {};
  62210. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62211. serializationObject.activeParticleCount = this.activeParticleCount;
  62212. return serializationObject;
  62213. };
  62214. /**
  62215. * Parses a JSON object to create a GPU particle system.
  62216. * @param parsedParticleSystem The JSON object to parse
  62217. * @param scene The scene to create the particle system in
  62218. * @param rootUrl The root url to use to load external dependencies like texture
  62219. * @returns the parsed GPU particle system
  62220. */
  62221. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62222. var name = parsedParticleSystem.name;
  62223. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62224. if (parsedParticleSystem.activeParticleCount) {
  62225. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62226. }
  62227. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62228. return particleSystem;
  62229. };
  62230. return GPUParticleSystem;
  62231. }(BABYLON.BaseParticleSystem));
  62232. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62233. })(BABYLON || (BABYLON = {}));
  62234. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62235. var BABYLON;
  62236. (function (BABYLON) {
  62237. /**
  62238. * Represents one particle of a solid particle system.
  62239. */
  62240. var SolidParticle = /** @class */ (function () {
  62241. /**
  62242. * Creates a Solid Particle object.
  62243. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62244. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62245. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62246. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62247. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62248. * @param shapeId (integer) is the model shape identifier in the SPS.
  62249. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62250. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62251. */
  62252. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62253. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62254. /**
  62255. * particle global index
  62256. */
  62257. this.idx = 0;
  62258. /**
  62259. * The color of the particle
  62260. */
  62261. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62262. /**
  62263. * The world space position of the particle.
  62264. */
  62265. this.position = BABYLON.Vector3.Zero();
  62266. /**
  62267. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62268. */
  62269. this.rotation = BABYLON.Vector3.Zero();
  62270. /**
  62271. * The scaling of the particle.
  62272. */
  62273. this.scaling = BABYLON.Vector3.One();
  62274. /**
  62275. * The uvs of the particle.
  62276. */
  62277. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62278. /**
  62279. * The current speed of the particle.
  62280. */
  62281. this.velocity = BABYLON.Vector3.Zero();
  62282. /**
  62283. * The pivot point in the particle local space.
  62284. */
  62285. this.pivot = BABYLON.Vector3.Zero();
  62286. /**
  62287. * Must the particle be translated from its pivot point in its local space ?
  62288. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62289. * Default : false
  62290. */
  62291. this.translateFromPivot = false;
  62292. /**
  62293. * Is the particle active or not ?
  62294. */
  62295. this.alive = true;
  62296. /**
  62297. * Is the particle visible or not ?
  62298. */
  62299. this.isVisible = true;
  62300. /**
  62301. * Index of this particle in the global "positions" array (Internal use)
  62302. * @hidden
  62303. */
  62304. this._pos = 0;
  62305. /**
  62306. * @hidden Index of this particle in the global "indices" array (Internal use)
  62307. */
  62308. this._ind = 0;
  62309. /**
  62310. * ModelShape id of this particle
  62311. */
  62312. this.shapeId = 0;
  62313. /**
  62314. * Index of the particle in its shape id (Internal use)
  62315. */
  62316. this.idxInShape = 0;
  62317. /**
  62318. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62319. */
  62320. this._stillInvisible = false;
  62321. /**
  62322. * @hidden Last computed particle rotation matrix
  62323. */
  62324. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62325. /**
  62326. * Parent particle Id, if any.
  62327. * Default null.
  62328. */
  62329. this.parentId = null;
  62330. /**
  62331. * @hidden Internal global position in the SPS.
  62332. */
  62333. this._globalPosition = BABYLON.Vector3.Zero();
  62334. this.idx = particleIndex;
  62335. this._pos = positionIndex;
  62336. this._ind = indiceIndex;
  62337. this._model = model;
  62338. this.shapeId = shapeId;
  62339. this.idxInShape = idxInShape;
  62340. this._sps = sps;
  62341. if (modelBoundingInfo) {
  62342. this._modelBoundingInfo = modelBoundingInfo;
  62343. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62344. }
  62345. }
  62346. Object.defineProperty(SolidParticle.prototype, "scale", {
  62347. /**
  62348. * Legacy support, changed scale to scaling
  62349. */
  62350. get: function () {
  62351. return this.scaling;
  62352. },
  62353. /**
  62354. * Legacy support, changed scale to scaling
  62355. */
  62356. set: function (scale) {
  62357. this.scaling = scale;
  62358. },
  62359. enumerable: true,
  62360. configurable: true
  62361. });
  62362. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62363. /**
  62364. * Legacy support, changed quaternion to rotationQuaternion
  62365. */
  62366. get: function () {
  62367. return this.rotationQuaternion;
  62368. },
  62369. /**
  62370. * Legacy support, changed quaternion to rotationQuaternion
  62371. */
  62372. set: function (q) {
  62373. this.rotationQuaternion = q;
  62374. },
  62375. enumerable: true,
  62376. configurable: true
  62377. });
  62378. /**
  62379. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62380. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62381. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62382. * @returns true if it intersects
  62383. */
  62384. SolidParticle.prototype.intersectsMesh = function (target) {
  62385. if (!this._boundingInfo || !target._boundingInfo) {
  62386. return false;
  62387. }
  62388. if (this._sps._bSphereOnly) {
  62389. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62390. }
  62391. return this._boundingInfo.intersects(target._boundingInfo, false);
  62392. };
  62393. return SolidParticle;
  62394. }());
  62395. BABYLON.SolidParticle = SolidParticle;
  62396. /**
  62397. * Represents the shape of the model used by one particle of a solid particle system.
  62398. * SPS internal tool, don't use it manually.
  62399. */
  62400. var ModelShape = /** @class */ (function () {
  62401. /**
  62402. * 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.
  62403. * SPS internal tool, don't use it manually.
  62404. * @hidden
  62405. */
  62406. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62407. /**
  62408. * length of the shape in the model indices array (internal use)
  62409. * @hidden
  62410. */
  62411. this._indicesLength = 0;
  62412. this.shapeID = id;
  62413. this._shape = shape;
  62414. this._indicesLength = indicesLength;
  62415. this._shapeUV = shapeUV;
  62416. this._positionFunction = posFunction;
  62417. this._vertexFunction = vtxFunction;
  62418. }
  62419. return ModelShape;
  62420. }());
  62421. BABYLON.ModelShape = ModelShape;
  62422. /**
  62423. * Represents a Depth Sorted Particle in the solid particle system.
  62424. */
  62425. var DepthSortedParticle = /** @class */ (function () {
  62426. function DepthSortedParticle() {
  62427. /**
  62428. * Index of the particle in the "indices" array
  62429. */
  62430. this.ind = 0;
  62431. /**
  62432. * Length of the particle shape in the "indices" array
  62433. */
  62434. this.indicesLength = 0;
  62435. /**
  62436. * Squared distance from the particle to the camera
  62437. */
  62438. this.sqDistance = 0.0;
  62439. }
  62440. return DepthSortedParticle;
  62441. }());
  62442. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62443. })(BABYLON || (BABYLON = {}));
  62444. //# sourceMappingURL=babylon.solidParticle.js.map
  62445. var BABYLON;
  62446. (function (BABYLON) {
  62447. /**
  62448. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62449. *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.
  62450. * The SPS is also a particle system. It provides some methods to manage the particles.
  62451. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62452. *
  62453. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62454. */
  62455. var SolidParticleSystem = /** @class */ (function () {
  62456. /**
  62457. * Creates a SPS (Solid Particle System) object.
  62458. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62459. * @param scene (Scene) is the scene in which the SPS is added.
  62460. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62461. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62462. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62463. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62464. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62465. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62466. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62467. */
  62468. function SolidParticleSystem(name, scene, options) {
  62469. /**
  62470. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62471. * Example : var p = SPS.particles[i];
  62472. */
  62473. this.particles = new Array();
  62474. /**
  62475. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62476. */
  62477. this.nbParticles = 0;
  62478. /**
  62479. * If the particles must ever face the camera (default false). Useful for planar particles.
  62480. */
  62481. this.billboard = false;
  62482. /**
  62483. * Recompute normals when adding a shape
  62484. */
  62485. this.recomputeNormals = true;
  62486. /**
  62487. * This a counter ofr your own usage. It's not set by any SPS functions.
  62488. */
  62489. this.counter = 0;
  62490. /**
  62491. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62492. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62493. */
  62494. this.vars = {};
  62495. /**
  62496. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62497. * @hidden
  62498. */
  62499. this._bSphereOnly = false;
  62500. /**
  62501. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62502. * @hidden
  62503. */
  62504. this._bSphereRadiusFactor = 1.0;
  62505. this._positions = new Array();
  62506. this._indices = new Array();
  62507. this._normals = new Array();
  62508. this._colors = new Array();
  62509. this._uvs = new Array();
  62510. this._index = 0; // indices index
  62511. this._updatable = true;
  62512. this._pickable = false;
  62513. this._isVisibilityBoxLocked = false;
  62514. this._alwaysVisible = false;
  62515. this._depthSort = false;
  62516. this._shapeCounter = 0;
  62517. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62518. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62519. this._computeParticleColor = true;
  62520. this._computeParticleTexture = true;
  62521. this._computeParticleRotation = true;
  62522. this._computeParticleVertex = false;
  62523. this._computeBoundingBox = false;
  62524. this._depthSortParticles = true;
  62525. this._cam_axisZ = BABYLON.Vector3.Zero();
  62526. this._cam_axisY = BABYLON.Vector3.Zero();
  62527. this._cam_axisX = BABYLON.Vector3.Zero();
  62528. this._axisZ = BABYLON.Axis.Z;
  62529. this._camDir = BABYLON.Vector3.Zero();
  62530. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62531. this._rotMatrix = new BABYLON.Matrix();
  62532. this._invertMatrix = new BABYLON.Matrix();
  62533. this._rotated = BABYLON.Vector3.Zero();
  62534. this._quaternion = new BABYLON.Quaternion();
  62535. this._vertex = BABYLON.Vector3.Zero();
  62536. this._normal = BABYLON.Vector3.Zero();
  62537. this._yaw = 0.0;
  62538. this._pitch = 0.0;
  62539. this._roll = 0.0;
  62540. this._halfroll = 0.0;
  62541. this._halfpitch = 0.0;
  62542. this._halfyaw = 0.0;
  62543. this._sinRoll = 0.0;
  62544. this._cosRoll = 0.0;
  62545. this._sinPitch = 0.0;
  62546. this._cosPitch = 0.0;
  62547. this._sinYaw = 0.0;
  62548. this._cosYaw = 0.0;
  62549. this._mustUnrotateFixedNormals = false;
  62550. this._minimum = BABYLON.Vector3.Zero();
  62551. this._maximum = BABYLON.Vector3.Zero();
  62552. this._minBbox = BABYLON.Vector3.Zero();
  62553. this._maxBbox = BABYLON.Vector3.Zero();
  62554. this._particlesIntersect = false;
  62555. this._depthSortFunction = function (p1, p2) {
  62556. return (p2.sqDistance - p1.sqDistance);
  62557. };
  62558. this._needs32Bits = false;
  62559. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62560. this._scaledPivot = BABYLON.Vector3.Zero();
  62561. this._particleHasParent = false;
  62562. this.name = name;
  62563. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62564. this._camera = scene.activeCamera;
  62565. this._pickable = options ? options.isPickable : false;
  62566. this._depthSort = options ? options.enableDepthSort : false;
  62567. this._particlesIntersect = options ? options.particleIntersection : false;
  62568. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62569. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62570. if (options && options.updatable !== undefined) {
  62571. this._updatable = options.updatable;
  62572. }
  62573. else {
  62574. this._updatable = true;
  62575. }
  62576. if (this._pickable) {
  62577. this.pickedParticles = [];
  62578. }
  62579. if (this._depthSort) {
  62580. this.depthSortedParticles = [];
  62581. }
  62582. }
  62583. /**
  62584. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62585. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62586. * @returns the created mesh
  62587. */
  62588. SolidParticleSystem.prototype.buildMesh = function () {
  62589. if (this.nbParticles === 0) {
  62590. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62591. this.addShape(triangle, 1);
  62592. triangle.dispose();
  62593. }
  62594. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62595. this._positions32 = new Float32Array(this._positions);
  62596. this._uvs32 = new Float32Array(this._uvs);
  62597. this._colors32 = new Float32Array(this._colors);
  62598. if (this.recomputeNormals) {
  62599. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62600. }
  62601. this._normals32 = new Float32Array(this._normals);
  62602. this._fixedNormal32 = new Float32Array(this._normals);
  62603. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62604. this._unrotateFixedNormals();
  62605. }
  62606. var vertexData = new BABYLON.VertexData();
  62607. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62608. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62609. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62610. if (this._uvs32.length > 0) {
  62611. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62612. }
  62613. if (this._colors32.length > 0) {
  62614. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62615. }
  62616. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62617. vertexData.applyToMesh(mesh, this._updatable);
  62618. this.mesh = mesh;
  62619. this.mesh.isPickable = this._pickable;
  62620. // free memory
  62621. if (!this._depthSort) {
  62622. this._indices = null;
  62623. }
  62624. this._positions = null;
  62625. this._normals = null;
  62626. this._uvs = null;
  62627. this._colors = null;
  62628. if (!this._updatable) {
  62629. this.particles.length = 0;
  62630. }
  62631. return mesh;
  62632. };
  62633. /**
  62634. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62635. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62636. * Thus the particles generated from `digest()` have their property `position` set yet.
  62637. * @param mesh ( Mesh ) is the mesh to be digested
  62638. * @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
  62639. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62640. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62641. * @returns the current SPS
  62642. */
  62643. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62644. var size = (options && options.facetNb) || 1;
  62645. var number = (options && options.number) || 0;
  62646. var delta = (options && options.delta) || 0;
  62647. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62648. var meshInd = mesh.getIndices();
  62649. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62650. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62651. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62652. var f = 0; // facet counter
  62653. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62654. // compute size from number
  62655. if (number) {
  62656. number = (number > totalFacets) ? totalFacets : number;
  62657. size = Math.round(totalFacets / number);
  62658. delta = 0;
  62659. }
  62660. else {
  62661. size = (size > totalFacets) ? totalFacets : size;
  62662. }
  62663. var facetPos = []; // submesh positions
  62664. var facetInd = []; // submesh indices
  62665. var facetUV = []; // submesh UV
  62666. var facetCol = []; // submesh colors
  62667. var barycenter = BABYLON.Vector3.Zero();
  62668. var sizeO = size;
  62669. while (f < totalFacets) {
  62670. size = sizeO + Math.floor((1 + delta) * Math.random());
  62671. if (f > totalFacets - size) {
  62672. size = totalFacets - f;
  62673. }
  62674. // reset temp arrays
  62675. facetPos.length = 0;
  62676. facetInd.length = 0;
  62677. facetUV.length = 0;
  62678. facetCol.length = 0;
  62679. // iterate over "size" facets
  62680. var fi = 0;
  62681. for (var j = f * 3; j < (f + size) * 3; j++) {
  62682. facetInd.push(fi);
  62683. var i = meshInd[j];
  62684. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62685. if (meshUV) {
  62686. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62687. }
  62688. if (meshCol) {
  62689. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62690. }
  62691. fi++;
  62692. }
  62693. // create a model shape for each single particle
  62694. var idx = this.nbParticles;
  62695. var shape = this._posToShape(facetPos);
  62696. var shapeUV = this._uvsToShapeUV(facetUV);
  62697. // compute the barycenter of the shape
  62698. var v;
  62699. for (v = 0; v < shape.length; v++) {
  62700. barycenter.addInPlace(shape[v]);
  62701. }
  62702. barycenter.scaleInPlace(1 / shape.length);
  62703. // shift the shape from its barycenter to the origin
  62704. for (v = 0; v < shape.length; v++) {
  62705. shape[v].subtractInPlace(barycenter);
  62706. }
  62707. var bInfo;
  62708. if (this._particlesIntersect) {
  62709. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62710. }
  62711. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62712. // add the particle in the SPS
  62713. var currentPos = this._positions.length;
  62714. var currentInd = this._indices.length;
  62715. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62716. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62717. // initialize the particle position
  62718. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62719. this._index += shape.length;
  62720. idx++;
  62721. this.nbParticles++;
  62722. this._shapeCounter++;
  62723. f += size;
  62724. }
  62725. return this;
  62726. };
  62727. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62728. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62729. var index = 0;
  62730. var idx = 0;
  62731. for (var p = 0; p < this.particles.length; p++) {
  62732. this._particle = this.particles[p];
  62733. this._shape = this._particle._model._shape;
  62734. if (this._particle.rotationQuaternion) {
  62735. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62736. }
  62737. else {
  62738. this._yaw = this._particle.rotation.y;
  62739. this._pitch = this._particle.rotation.x;
  62740. this._roll = this._particle.rotation.z;
  62741. this._quaternionRotationYPR();
  62742. }
  62743. this._quaternionToRotationMatrix();
  62744. this._rotMatrix.invertToRef(this._invertMatrix);
  62745. for (var pt = 0; pt < this._shape.length; pt++) {
  62746. idx = index + pt * 3;
  62747. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62748. this._fixedNormal32[idx] = this._normal.x;
  62749. this._fixedNormal32[idx + 1] = this._normal.y;
  62750. this._fixedNormal32[idx + 2] = this._normal.z;
  62751. }
  62752. index = idx + 3;
  62753. }
  62754. };
  62755. //reset copy
  62756. SolidParticleSystem.prototype._resetCopy = function () {
  62757. this._copy.position.x = 0;
  62758. this._copy.position.y = 0;
  62759. this._copy.position.z = 0;
  62760. this._copy.rotation.x = 0;
  62761. this._copy.rotation.y = 0;
  62762. this._copy.rotation.z = 0;
  62763. this._copy.rotationQuaternion = null;
  62764. this._copy.scaling.x = 1.0;
  62765. this._copy.scaling.y = 1.0;
  62766. this._copy.scaling.z = 1.0;
  62767. this._copy.uvs.x = 0;
  62768. this._copy.uvs.y = 0;
  62769. this._copy.uvs.z = 1.0;
  62770. this._copy.uvs.w = 1.0;
  62771. this._copy.color = null;
  62772. this._copy.translateFromPivot = false;
  62773. };
  62774. // _meshBuilder : inserts the shape model in the global SPS mesh
  62775. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62776. var i;
  62777. var u = 0;
  62778. var c = 0;
  62779. var n = 0;
  62780. this._resetCopy();
  62781. if (options && options.positionFunction) { // call to custom positionFunction
  62782. options.positionFunction(this._copy, idx, idxInShape);
  62783. this._mustUnrotateFixedNormals = true;
  62784. }
  62785. if (this._copy.rotationQuaternion) {
  62786. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62787. }
  62788. else {
  62789. this._yaw = this._copy.rotation.y;
  62790. this._pitch = this._copy.rotation.x;
  62791. this._roll = this._copy.rotation.z;
  62792. this._quaternionRotationYPR();
  62793. }
  62794. this._quaternionToRotationMatrix();
  62795. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62796. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62797. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62798. if (this._copy.translateFromPivot) {
  62799. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62800. }
  62801. else {
  62802. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62803. }
  62804. for (i = 0; i < shape.length; i++) {
  62805. this._vertex.x = shape[i].x;
  62806. this._vertex.y = shape[i].y;
  62807. this._vertex.z = shape[i].z;
  62808. if (options && options.vertexFunction) {
  62809. options.vertexFunction(this._copy, this._vertex, i);
  62810. }
  62811. this._vertex.x *= this._copy.scaling.x;
  62812. this._vertex.y *= this._copy.scaling.y;
  62813. this._vertex.z *= this._copy.scaling.z;
  62814. this._vertex.x -= this._scaledPivot.x;
  62815. this._vertex.y -= this._scaledPivot.y;
  62816. this._vertex.z -= this._scaledPivot.z;
  62817. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62818. this._rotated.addInPlace(this._pivotBackTranslation);
  62819. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62820. if (meshUV) {
  62821. 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);
  62822. u += 2;
  62823. }
  62824. if (this._copy.color) {
  62825. this._color = this._copy.color;
  62826. }
  62827. else if (meshCol && meshCol[c] !== undefined) {
  62828. this._color.r = meshCol[c];
  62829. this._color.g = meshCol[c + 1];
  62830. this._color.b = meshCol[c + 2];
  62831. this._color.a = meshCol[c + 3];
  62832. }
  62833. else {
  62834. this._color.r = 1.0;
  62835. this._color.g = 1.0;
  62836. this._color.b = 1.0;
  62837. this._color.a = 1.0;
  62838. }
  62839. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62840. c += 4;
  62841. if (!this.recomputeNormals && meshNor) {
  62842. this._normal.x = meshNor[n];
  62843. this._normal.y = meshNor[n + 1];
  62844. this._normal.z = meshNor[n + 2];
  62845. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62846. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62847. n += 3;
  62848. }
  62849. }
  62850. for (i = 0; i < meshInd.length; i++) {
  62851. var current_ind = p + meshInd[i];
  62852. indices.push(current_ind);
  62853. if (current_ind > 65535) {
  62854. this._needs32Bits = true;
  62855. }
  62856. }
  62857. if (this._pickable) {
  62858. var nbfaces = meshInd.length / 3;
  62859. for (i = 0; i < nbfaces; i++) {
  62860. this.pickedParticles.push({ idx: idx, faceId: i });
  62861. }
  62862. }
  62863. if (this._depthSort) {
  62864. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62865. }
  62866. return this._copy;
  62867. };
  62868. // returns a shape array from positions array
  62869. SolidParticleSystem.prototype._posToShape = function (positions) {
  62870. var shape = [];
  62871. for (var i = 0; i < positions.length; i += 3) {
  62872. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62873. }
  62874. return shape;
  62875. };
  62876. // returns a shapeUV array from a Vector4 uvs
  62877. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62878. var shapeUV = [];
  62879. if (uvs) {
  62880. for (var i = 0; i < uvs.length; i++)
  62881. shapeUV.push(uvs[i]);
  62882. }
  62883. return shapeUV;
  62884. };
  62885. // adds a new particle object in the particles array
  62886. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62887. if (bInfo === void 0) { bInfo = null; }
  62888. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62889. this.particles.push(sp);
  62890. return sp;
  62891. };
  62892. /**
  62893. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62894. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62895. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62896. * @param nb (positive integer) the number of particles to be created from this model
  62897. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62898. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62899. * @returns the number of shapes in the system
  62900. */
  62901. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62902. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62903. var meshInd = mesh.getIndices();
  62904. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62905. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62906. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62907. var bbInfo;
  62908. if (this._particlesIntersect) {
  62909. bbInfo = mesh.getBoundingInfo();
  62910. }
  62911. var shape = this._posToShape(meshPos);
  62912. var shapeUV = this._uvsToShapeUV(meshUV);
  62913. var posfunc = options ? options.positionFunction : null;
  62914. var vtxfunc = options ? options.vertexFunction : null;
  62915. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62916. // particles
  62917. var sp;
  62918. var currentCopy;
  62919. var idx = this.nbParticles;
  62920. for (var i = 0; i < nb; i++) {
  62921. var currentPos = this._positions.length;
  62922. var currentInd = this._indices.length;
  62923. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62924. if (this._updatable) {
  62925. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62926. sp.position.copyFrom(currentCopy.position);
  62927. sp.rotation.copyFrom(currentCopy.rotation);
  62928. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62929. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62930. }
  62931. if (currentCopy.color && sp.color) {
  62932. sp.color.copyFrom(currentCopy.color);
  62933. }
  62934. sp.scaling.copyFrom(currentCopy.scaling);
  62935. sp.uvs.copyFrom(currentCopy.uvs);
  62936. }
  62937. this._index += shape.length;
  62938. idx++;
  62939. }
  62940. this.nbParticles += nb;
  62941. this._shapeCounter++;
  62942. return this._shapeCounter - 1;
  62943. };
  62944. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62945. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62946. this._resetCopy();
  62947. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62948. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62949. }
  62950. if (this._copy.rotationQuaternion) {
  62951. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62952. }
  62953. else {
  62954. this._yaw = this._copy.rotation.y;
  62955. this._pitch = this._copy.rotation.x;
  62956. this._roll = this._copy.rotation.z;
  62957. this._quaternionRotationYPR();
  62958. }
  62959. this._quaternionToRotationMatrix();
  62960. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62961. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62962. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62963. if (this._copy.translateFromPivot) {
  62964. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62965. }
  62966. else {
  62967. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62968. }
  62969. this._shape = particle._model._shape;
  62970. for (var pt = 0; pt < this._shape.length; pt++) {
  62971. this._vertex.x = this._shape[pt].x;
  62972. this._vertex.y = this._shape[pt].y;
  62973. this._vertex.z = this._shape[pt].z;
  62974. if (particle._model._vertexFunction) {
  62975. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62976. }
  62977. this._vertex.x *= this._copy.scaling.x;
  62978. this._vertex.y *= this._copy.scaling.y;
  62979. this._vertex.z *= this._copy.scaling.z;
  62980. this._vertex.x -= this._scaledPivot.x;
  62981. this._vertex.y -= this._scaledPivot.y;
  62982. this._vertex.z -= this._scaledPivot.z;
  62983. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62984. this._rotated.addInPlace(this._pivotBackTranslation);
  62985. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62986. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62987. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62988. }
  62989. particle.position.x = 0.0;
  62990. particle.position.y = 0.0;
  62991. particle.position.z = 0.0;
  62992. particle.rotation.x = 0.0;
  62993. particle.rotation.y = 0.0;
  62994. particle.rotation.z = 0.0;
  62995. particle.rotationQuaternion = null;
  62996. particle.scaling.x = 1.0;
  62997. particle.scaling.y = 1.0;
  62998. particle.scaling.z = 1.0;
  62999. particle.uvs.x = 0.0;
  63000. particle.uvs.y = 0.0;
  63001. particle.uvs.z = 1.0;
  63002. particle.uvs.w = 1.0;
  63003. particle.pivot.x = 0.0;
  63004. particle.pivot.y = 0.0;
  63005. particle.pivot.z = 0.0;
  63006. particle.translateFromPivot = false;
  63007. particle.parentId = null;
  63008. };
  63009. /**
  63010. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63011. * @returns the SPS.
  63012. */
  63013. SolidParticleSystem.prototype.rebuildMesh = function () {
  63014. for (var p = 0; p < this.particles.length; p++) {
  63015. this._rebuildParticle(this.particles[p]);
  63016. }
  63017. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63018. return this;
  63019. };
  63020. /**
  63021. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63022. * This method calls `updateParticle()` for each particle of the SPS.
  63023. * For an animated SPS, it is usually called within the render loop.
  63024. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63025. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63026. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63027. * @returns the SPS.
  63028. */
  63029. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63030. if (start === void 0) { start = 0; }
  63031. if (end === void 0) { end = this.nbParticles - 1; }
  63032. if (update === void 0) { update = true; }
  63033. if (!this._updatable) {
  63034. return this;
  63035. }
  63036. // custom beforeUpdate
  63037. this.beforeUpdateParticles(start, end, update);
  63038. this._cam_axisX.x = 1.0;
  63039. this._cam_axisX.y = 0.0;
  63040. this._cam_axisX.z = 0.0;
  63041. this._cam_axisY.x = 0.0;
  63042. this._cam_axisY.y = 1.0;
  63043. this._cam_axisY.z = 0.0;
  63044. this._cam_axisZ.x = 0.0;
  63045. this._cam_axisZ.y = 0.0;
  63046. this._cam_axisZ.z = 1.0;
  63047. // cases when the World Matrix is to be computed first
  63048. if (this.billboard || this._depthSort) {
  63049. this.mesh.computeWorldMatrix(true);
  63050. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63051. }
  63052. // if the particles will always face the camera
  63053. if (this.billboard) {
  63054. // compute the camera position and un-rotate it by the current mesh rotation
  63055. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63056. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63057. this._cam_axisZ.normalize();
  63058. // same for camera up vector extracted from the cam view matrix
  63059. var view = this._camera.getViewMatrix(true);
  63060. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63061. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63062. this._cam_axisY.normalize();
  63063. this._cam_axisX.normalize();
  63064. }
  63065. // if depthSort, compute the camera global position in the mesh local system
  63066. if (this._depthSort) {
  63067. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63068. }
  63069. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63070. var idx = 0; // current position index in the global array positions32
  63071. var index = 0; // position start index in the global array positions32 of the current particle
  63072. var colidx = 0; // current color index in the global array colors32
  63073. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63074. var uvidx = 0; // current uv index in the global array uvs32
  63075. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63076. var pt = 0; // current index in the particle model shape
  63077. if (this.mesh.isFacetDataEnabled) {
  63078. this._computeBoundingBox = true;
  63079. }
  63080. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63081. if (this._computeBoundingBox) {
  63082. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63083. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63084. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63085. }
  63086. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63087. if (this.mesh._boundingInfo) {
  63088. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63089. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63090. }
  63091. }
  63092. }
  63093. // particle loop
  63094. index = this.particles[start]._pos;
  63095. var vpos = (index / 3) | 0;
  63096. colorIndex = vpos * 4;
  63097. uvIndex = vpos * 2;
  63098. for (var p = start; p <= end; p++) {
  63099. this._particle = this.particles[p];
  63100. this._shape = this._particle._model._shape;
  63101. this._shapeUV = this._particle._model._shapeUV;
  63102. // call to custom user function to update the particle properties
  63103. this.updateParticle(this._particle);
  63104. // camera-particle distance for depth sorting
  63105. if (this._depthSort && this._depthSortParticles) {
  63106. var dsp = this.depthSortedParticles[p];
  63107. dsp.ind = this._particle._ind;
  63108. dsp.indicesLength = this._particle._model._indicesLength;
  63109. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63110. }
  63111. // skip the computations for inactive or already invisible particles
  63112. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63113. // increment indexes for the next particle
  63114. pt = this._shape.length;
  63115. index += pt * 3;
  63116. colorIndex += pt * 4;
  63117. uvIndex += pt * 2;
  63118. continue;
  63119. }
  63120. if (this._particle.isVisible) {
  63121. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63122. this._particleHasParent = (this._particle.parentId !== null);
  63123. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63124. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63125. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63126. // particle rotation matrix
  63127. if (this.billboard) {
  63128. this._particle.rotation.x = 0.0;
  63129. this._particle.rotation.y = 0.0;
  63130. }
  63131. if (this._computeParticleRotation || this.billboard) {
  63132. if (this._particle.rotationQuaternion) {
  63133. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63134. }
  63135. else {
  63136. this._yaw = this._particle.rotation.y;
  63137. this._pitch = this._particle.rotation.x;
  63138. this._roll = this._particle.rotation.z;
  63139. this._quaternionRotationYPR();
  63140. }
  63141. this._quaternionToRotationMatrix();
  63142. }
  63143. if (this._particleHasParent) {
  63144. this._parent = this.particles[this._particle.parentId];
  63145. 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];
  63146. 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];
  63147. 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];
  63148. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63149. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63150. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63151. if (this._computeParticleRotation || this.billboard) {
  63152. 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];
  63153. 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];
  63154. 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];
  63155. 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];
  63156. 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];
  63157. 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];
  63158. 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];
  63159. 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];
  63160. 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];
  63161. }
  63162. }
  63163. else {
  63164. this._particle._globalPosition.x = this._particle.position.x;
  63165. this._particle._globalPosition.y = this._particle.position.y;
  63166. this._particle._globalPosition.z = this._particle.position.z;
  63167. if (this._computeParticleRotation || this.billboard) {
  63168. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63169. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63170. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63171. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63172. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63173. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63174. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63175. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63176. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63177. }
  63178. }
  63179. if (this._particle.translateFromPivot) {
  63180. this._pivotBackTranslation.x = 0.0;
  63181. this._pivotBackTranslation.y = 0.0;
  63182. this._pivotBackTranslation.z = 0.0;
  63183. }
  63184. else {
  63185. this._pivotBackTranslation.x = this._scaledPivot.x;
  63186. this._pivotBackTranslation.y = this._scaledPivot.y;
  63187. this._pivotBackTranslation.z = this._scaledPivot.z;
  63188. }
  63189. // particle vertex loop
  63190. for (pt = 0; pt < this._shape.length; pt++) {
  63191. idx = index + pt * 3;
  63192. colidx = colorIndex + pt * 4;
  63193. uvidx = uvIndex + pt * 2;
  63194. this._vertex.x = this._shape[pt].x;
  63195. this._vertex.y = this._shape[pt].y;
  63196. this._vertex.z = this._shape[pt].z;
  63197. if (this._computeParticleVertex) {
  63198. this.updateParticleVertex(this._particle, this._vertex, pt);
  63199. }
  63200. // positions
  63201. this._vertex.x *= this._particle.scaling.x;
  63202. this._vertex.y *= this._particle.scaling.y;
  63203. this._vertex.z *= this._particle.scaling.z;
  63204. this._vertex.x -= this._scaledPivot.x;
  63205. this._vertex.y -= this._scaledPivot.y;
  63206. this._vertex.z -= this._scaledPivot.z;
  63207. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63208. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63209. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63210. this._rotated.x += this._pivotBackTranslation.x;
  63211. this._rotated.y += this._pivotBackTranslation.y;
  63212. this._rotated.z += this._pivotBackTranslation.z;
  63213. 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;
  63214. 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;
  63215. 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;
  63216. if (this._computeBoundingBox) {
  63217. if (this._positions32[idx] < this._minimum.x) {
  63218. this._minimum.x = this._positions32[idx];
  63219. }
  63220. if (this._positions32[idx] > this._maximum.x) {
  63221. this._maximum.x = this._positions32[idx];
  63222. }
  63223. if (this._positions32[idx + 1] < this._minimum.y) {
  63224. this._minimum.y = this._positions32[idx + 1];
  63225. }
  63226. if (this._positions32[idx + 1] > this._maximum.y) {
  63227. this._maximum.y = this._positions32[idx + 1];
  63228. }
  63229. if (this._positions32[idx + 2] < this._minimum.z) {
  63230. this._minimum.z = this._positions32[idx + 2];
  63231. }
  63232. if (this._positions32[idx + 2] > this._maximum.z) {
  63233. this._maximum.z = this._positions32[idx + 2];
  63234. }
  63235. }
  63236. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63237. if (!this._computeParticleVertex) {
  63238. this._normal.x = this._fixedNormal32[idx];
  63239. this._normal.y = this._fixedNormal32[idx + 1];
  63240. this._normal.z = this._fixedNormal32[idx + 2];
  63241. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63242. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63243. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63244. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63245. 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;
  63246. 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;
  63247. }
  63248. if (this._computeParticleColor && this._particle.color) {
  63249. this._colors32[colidx] = this._particle.color.r;
  63250. this._colors32[colidx + 1] = this._particle.color.g;
  63251. this._colors32[colidx + 2] = this._particle.color.b;
  63252. this._colors32[colidx + 3] = this._particle.color.a;
  63253. }
  63254. if (this._computeParticleTexture) {
  63255. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63256. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63257. }
  63258. }
  63259. }
  63260. // particle just set invisible : scaled to zero and positioned at the origin
  63261. else {
  63262. this._particle._stillInvisible = true; // mark the particle as invisible
  63263. for (pt = 0; pt < this._shape.length; pt++) {
  63264. idx = index + pt * 3;
  63265. colidx = colorIndex + pt * 4;
  63266. uvidx = uvIndex + pt * 2;
  63267. this._positions32[idx] = 0.0;
  63268. this._positions32[idx + 1] = 0.0;
  63269. this._positions32[idx + 2] = 0.0;
  63270. this._normals32[idx] = 0.0;
  63271. this._normals32[idx + 1] = 0.0;
  63272. this._normals32[idx + 2] = 0.0;
  63273. if (this._computeParticleColor && this._particle.color) {
  63274. this._colors32[colidx] = this._particle.color.r;
  63275. this._colors32[colidx + 1] = this._particle.color.g;
  63276. this._colors32[colidx + 2] = this._particle.color.b;
  63277. this._colors32[colidx + 3] = this._particle.color.a;
  63278. }
  63279. if (this._computeParticleTexture) {
  63280. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63281. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63282. }
  63283. }
  63284. }
  63285. // if the particle intersections must be computed : update the bbInfo
  63286. if (this._particlesIntersect) {
  63287. var bInfo = this._particle._boundingInfo;
  63288. var bBox = bInfo.boundingBox;
  63289. var bSphere = bInfo.boundingSphere;
  63290. if (!this._bSphereOnly) {
  63291. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63292. for (var b = 0; b < bBox.vectors.length; b++) {
  63293. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63294. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63295. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63296. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63297. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63298. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63299. 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;
  63300. 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;
  63301. 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;
  63302. }
  63303. bBox._update(this.mesh._worldMatrix);
  63304. }
  63305. // place and scale the particle bouding sphere in the SPS local system, then update it
  63306. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63307. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63308. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63309. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63310. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63311. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63312. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63313. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63314. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63315. 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));
  63316. bSphere._update(this.mesh._worldMatrix);
  63317. }
  63318. // increment indexes for the next particle
  63319. index = idx + 3;
  63320. colorIndex = colidx + 4;
  63321. uvIndex = uvidx + 2;
  63322. }
  63323. // if the VBO must be updated
  63324. if (update) {
  63325. if (this._computeParticleColor) {
  63326. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63327. }
  63328. if (this._computeParticleTexture) {
  63329. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63330. }
  63331. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63332. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63333. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63334. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63335. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63336. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63337. for (var i = 0; i < this._normals32.length; i++) {
  63338. this._fixedNormal32[i] = this._normals32[i];
  63339. }
  63340. }
  63341. if (!this.mesh.areNormalsFrozen) {
  63342. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63343. }
  63344. }
  63345. if (this._depthSort && this._depthSortParticles) {
  63346. this.depthSortedParticles.sort(this._depthSortFunction);
  63347. var dspl = this.depthSortedParticles.length;
  63348. var sorted = 0;
  63349. var lind = 0;
  63350. var sind = 0;
  63351. var sid = 0;
  63352. for (sorted = 0; sorted < dspl; sorted++) {
  63353. lind = this.depthSortedParticles[sorted].indicesLength;
  63354. sind = this.depthSortedParticles[sorted].ind;
  63355. for (var i = 0; i < lind; i++) {
  63356. this._indices32[sid] = this._indices[sind + i];
  63357. sid++;
  63358. }
  63359. }
  63360. this.mesh.updateIndices(this._indices32);
  63361. }
  63362. }
  63363. if (this._computeBoundingBox) {
  63364. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63365. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63366. }
  63367. this.afterUpdateParticles(start, end, update);
  63368. return this;
  63369. };
  63370. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63371. this._halfroll = this._roll * 0.5;
  63372. this._halfpitch = this._pitch * 0.5;
  63373. this._halfyaw = this._yaw * 0.5;
  63374. this._sinRoll = Math.sin(this._halfroll);
  63375. this._cosRoll = Math.cos(this._halfroll);
  63376. this._sinPitch = Math.sin(this._halfpitch);
  63377. this._cosPitch = Math.cos(this._halfpitch);
  63378. this._sinYaw = Math.sin(this._halfyaw);
  63379. this._cosYaw = Math.cos(this._halfyaw);
  63380. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63381. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63382. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63383. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63384. };
  63385. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63386. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63387. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63388. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63389. this._rotMatrix.m[3] = 0;
  63390. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63391. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63392. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63393. this._rotMatrix.m[7] = 0;
  63394. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63395. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63396. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63397. this._rotMatrix.m[11] = 0;
  63398. this._rotMatrix.m[12] = 0;
  63399. this._rotMatrix.m[13] = 0;
  63400. this._rotMatrix.m[14] = 0;
  63401. this._rotMatrix.m[15] = 1.0;
  63402. };
  63403. /**
  63404. * Disposes the SPS.
  63405. */
  63406. SolidParticleSystem.prototype.dispose = function () {
  63407. this.mesh.dispose();
  63408. this.vars = null;
  63409. // drop references to internal big arrays for the GC
  63410. this._positions = null;
  63411. this._indices = null;
  63412. this._normals = null;
  63413. this._uvs = null;
  63414. this._colors = null;
  63415. this._indices32 = null;
  63416. this._positions32 = null;
  63417. this._normals32 = null;
  63418. this._fixedNormal32 = null;
  63419. this._uvs32 = null;
  63420. this._colors32 = null;
  63421. this.pickedParticles = null;
  63422. };
  63423. /**
  63424. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63425. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63426. * @returns the SPS.
  63427. */
  63428. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63429. if (!this._isVisibilityBoxLocked) {
  63430. this.mesh.refreshBoundingInfo();
  63431. }
  63432. return this;
  63433. };
  63434. /**
  63435. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63436. * @param size the size (float) of the visibility box
  63437. * note : this doesn't lock the SPS mesh bounding box.
  63438. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63439. */
  63440. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63441. var vis = size / 2;
  63442. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63443. };
  63444. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63445. /**
  63446. * Gets whether the SPS as always visible or not
  63447. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63448. */
  63449. get: function () {
  63450. return this._alwaysVisible;
  63451. },
  63452. /**
  63453. * Sets the SPS as always visible or not
  63454. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63455. */
  63456. set: function (val) {
  63457. this._alwaysVisible = val;
  63458. this.mesh.alwaysSelectAsActiveMesh = val;
  63459. },
  63460. enumerable: true,
  63461. configurable: true
  63462. });
  63463. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63464. /**
  63465. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63466. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63467. */
  63468. get: function () {
  63469. return this._isVisibilityBoxLocked;
  63470. },
  63471. /**
  63472. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63473. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63474. */
  63475. set: function (val) {
  63476. this._isVisibilityBoxLocked = val;
  63477. var boundingInfo = this.mesh.getBoundingInfo();
  63478. boundingInfo.isLocked = val;
  63479. },
  63480. enumerable: true,
  63481. configurable: true
  63482. });
  63483. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63484. /**
  63485. * Gets if `setParticles()` computes the particle rotations or not.
  63486. * Default value : true. The SPS is faster when it's set to false.
  63487. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63488. */
  63489. get: function () {
  63490. return this._computeParticleRotation;
  63491. },
  63492. /**
  63493. * Tells to `setParticles()` to compute the particle rotations or not.
  63494. * Default value : true. The SPS is faster when it's set to false.
  63495. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63496. */
  63497. set: function (val) {
  63498. this._computeParticleRotation = val;
  63499. },
  63500. enumerable: true,
  63501. configurable: true
  63502. });
  63503. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63504. /**
  63505. * Gets if `setParticles()` computes the particle colors or not.
  63506. * Default value : true. The SPS is faster when it's set to false.
  63507. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63508. */
  63509. get: function () {
  63510. return this._computeParticleColor;
  63511. },
  63512. /**
  63513. * Tells to `setParticles()` to compute the particle colors or not.
  63514. * Default value : true. The SPS is faster when it's set to false.
  63515. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63516. */
  63517. set: function (val) {
  63518. this._computeParticleColor = val;
  63519. },
  63520. enumerable: true,
  63521. configurable: true
  63522. });
  63523. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63524. /**
  63525. * Gets if `setParticles()` computes the particle textures or not.
  63526. * Default value : true. The SPS is faster when it's set to false.
  63527. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63528. */
  63529. get: function () {
  63530. return this._computeParticleTexture;
  63531. },
  63532. set: function (val) {
  63533. this._computeParticleTexture = val;
  63534. },
  63535. enumerable: true,
  63536. configurable: true
  63537. });
  63538. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63539. /**
  63540. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63541. * Default value : false. The SPS is faster when it's set to false.
  63542. * Note : the particle custom vertex positions aren't stored values.
  63543. */
  63544. get: function () {
  63545. return this._computeParticleVertex;
  63546. },
  63547. /**
  63548. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63549. * Default value : false. The SPS is faster when it's set to false.
  63550. * Note : the particle custom vertex positions aren't stored values.
  63551. */
  63552. set: function (val) {
  63553. this._computeParticleVertex = val;
  63554. },
  63555. enumerable: true,
  63556. configurable: true
  63557. });
  63558. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63559. /**
  63560. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63561. */
  63562. get: function () {
  63563. return this._computeBoundingBox;
  63564. },
  63565. /**
  63566. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63567. */
  63568. set: function (val) {
  63569. this._computeBoundingBox = val;
  63570. },
  63571. enumerable: true,
  63572. configurable: true
  63573. });
  63574. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63575. /**
  63576. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63577. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63578. * Default : `true`
  63579. */
  63580. get: function () {
  63581. return this._depthSortParticles;
  63582. },
  63583. /**
  63584. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63585. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63586. * Default : `true`
  63587. */
  63588. set: function (val) {
  63589. this._depthSortParticles = val;
  63590. },
  63591. enumerable: true,
  63592. configurable: true
  63593. });
  63594. // =======================================================================
  63595. // Particle behavior logic
  63596. // these following methods may be overwritten by the user to fit his needs
  63597. /**
  63598. * This function does nothing. It may be overwritten to set all the particle first values.
  63599. * The SPS doesn't call this function, you may have to call it by your own.
  63600. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63601. */
  63602. SolidParticleSystem.prototype.initParticles = function () {
  63603. };
  63604. /**
  63605. * This function does nothing. It may be overwritten to recycle a particle.
  63606. * The SPS doesn't call this function, you may have to call it by your own.
  63607. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63608. * @param particle The particle to recycle
  63609. * @returns the recycled particle
  63610. */
  63611. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63612. return particle;
  63613. };
  63614. /**
  63615. * Updates a particle : this function should be overwritten by the user.
  63616. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63617. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63618. * @example : just set a particle position or velocity and recycle conditions
  63619. * @param particle The particle to update
  63620. * @returns the updated particle
  63621. */
  63622. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63623. return particle;
  63624. };
  63625. /**
  63626. * Updates a vertex of a particle : it can be overwritten by the user.
  63627. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63628. * @param particle the current particle
  63629. * @param vertex the current index of the current particle
  63630. * @param pt the index of the current vertex in the particle shape
  63631. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63632. * @example : just set a vertex particle position
  63633. * @returns the updated vertex
  63634. */
  63635. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63636. return vertex;
  63637. };
  63638. /**
  63639. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63640. * This does nothing and may be overwritten by the user.
  63641. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63642. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63643. * @param update the boolean update value actually passed to setParticles()
  63644. */
  63645. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63646. };
  63647. /**
  63648. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63649. * This will be passed three parameters.
  63650. * This does nothing and may be overwritten by the user.
  63651. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63652. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63653. * @param update the boolean update value actually passed to setParticles()
  63654. */
  63655. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63656. };
  63657. return SolidParticleSystem;
  63658. }());
  63659. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63660. })(BABYLON || (BABYLON = {}));
  63661. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63662. var BABYLON;
  63663. (function (BABYLON) {
  63664. /**
  63665. * Class containing static functions to help procedurally build meshes
  63666. */
  63667. var MeshBuilder = /** @class */ (function () {
  63668. function MeshBuilder() {
  63669. }
  63670. MeshBuilder.updateSideOrientation = function (orientation) {
  63671. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63672. return BABYLON.Mesh.DOUBLESIDE;
  63673. }
  63674. if (orientation === undefined || orientation === null) {
  63675. return BABYLON.Mesh.FRONTSIDE;
  63676. }
  63677. return orientation;
  63678. };
  63679. /**
  63680. * Creates a box mesh
  63681. * * The parameter `size` sets the size (float) of each box side (default 1)
  63682. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63683. * * 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)
  63684. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63685. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63686. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63687. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63688. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63689. * @param name defines the name of the mesh
  63690. * @param options defines the options used to create the mesh
  63691. * @param scene defines the hosting scene
  63692. * @returns the box mesh
  63693. */
  63694. MeshBuilder.CreateBox = function (name, options, scene) {
  63695. if (scene === void 0) { scene = null; }
  63696. var box = new BABYLON.Mesh(name, scene);
  63697. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63698. box._originalBuilderSideOrientation = options.sideOrientation;
  63699. var vertexData = BABYLON.VertexData.CreateBox(options);
  63700. vertexData.applyToMesh(box, options.updatable);
  63701. return box;
  63702. };
  63703. /**
  63704. * Creates a sphere mesh
  63705. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63706. * * 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`)
  63707. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63708. * * 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
  63709. * * 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)
  63710. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63711. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63712. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63713. * @param name defines the name of the mesh
  63714. * @param options defines the options used to create the mesh
  63715. * @param scene defines the hosting scene
  63716. * @returns the sphere mesh
  63717. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63718. */
  63719. MeshBuilder.CreateSphere = function (name, options, scene) {
  63720. var sphere = new BABYLON.Mesh(name, scene);
  63721. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63722. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63723. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63724. vertexData.applyToMesh(sphere, options.updatable);
  63725. return sphere;
  63726. };
  63727. /**
  63728. * Creates a plane polygonal mesh. By default, this is a disc
  63729. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63730. * * 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
  63731. * * 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
  63732. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63733. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63734. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63735. * @param name defines the name of the mesh
  63736. * @param options defines the options used to create the mesh
  63737. * @param scene defines the hosting scene
  63738. * @returns the plane polygonal mesh
  63739. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63740. */
  63741. MeshBuilder.CreateDisc = function (name, options, scene) {
  63742. if (scene === void 0) { scene = null; }
  63743. var disc = new BABYLON.Mesh(name, scene);
  63744. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63745. disc._originalBuilderSideOrientation = options.sideOrientation;
  63746. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63747. vertexData.applyToMesh(disc, options.updatable);
  63748. return disc;
  63749. };
  63750. /**
  63751. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63752. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63753. * * 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`)
  63754. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63755. * * 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
  63756. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63757. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63758. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63759. * @param name defines the name of the mesh
  63760. * @param options defines the options used to create the mesh
  63761. * @param scene defines the hosting scene
  63762. * @returns the icosahedron mesh
  63763. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63764. */
  63765. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63766. var sphere = new BABYLON.Mesh(name, scene);
  63767. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63768. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63769. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63770. vertexData.applyToMesh(sphere, options.updatable);
  63771. return sphere;
  63772. };
  63773. ;
  63774. /**
  63775. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63776. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63777. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63778. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63779. * * 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
  63780. * * 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
  63781. * * 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
  63782. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63783. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63784. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63785. * * 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
  63786. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63787. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  63788. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63789. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63790. * @param name defines the name of the mesh
  63791. * @param options defines the options used to create the mesh
  63792. * @param scene defines the hosting scene
  63793. * @returns the ribbon mesh
  63794. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63795. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63796. */
  63797. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63798. if (scene === void 0) { scene = null; }
  63799. var pathArray = options.pathArray;
  63800. var closeArray = options.closeArray;
  63801. var closePath = options.closePath;
  63802. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63803. var instance = options.instance;
  63804. var updatable = options.updatable;
  63805. if (instance) { // existing ribbon instance update
  63806. // positionFunction : ribbon case
  63807. // only pathArray and sideOrientation parameters are taken into account for positions update
  63808. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63809. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63810. var positionFunction = function (positions) {
  63811. var minlg = pathArray[0].length;
  63812. var i = 0;
  63813. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63814. for (var si = 1; si <= ns; si++) {
  63815. for (var p = 0; p < pathArray.length; p++) {
  63816. var path = pathArray[p];
  63817. var l = path.length;
  63818. minlg = (minlg < l) ? minlg : l;
  63819. var j = 0;
  63820. while (j < minlg) {
  63821. positions[i] = path[j].x;
  63822. positions[i + 1] = path[j].y;
  63823. positions[i + 2] = path[j].z;
  63824. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63825. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63826. }
  63827. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63828. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63829. }
  63830. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63831. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63832. }
  63833. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63834. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63835. }
  63836. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63837. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63838. }
  63839. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63840. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63841. }
  63842. j++;
  63843. i += 3;
  63844. }
  63845. if (instance._closePath) {
  63846. positions[i] = path[0].x;
  63847. positions[i + 1] = path[0].y;
  63848. positions[i + 2] = path[0].z;
  63849. i += 3;
  63850. }
  63851. }
  63852. }
  63853. };
  63854. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63855. positionFunction(positions);
  63856. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63857. instance._boundingInfo.update(instance._worldMatrix);
  63858. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63859. if (options.colors) {
  63860. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63861. for (var c = 0; c < options.colors.length; c++) {
  63862. colors[c * 4] = options.colors[c].r;
  63863. colors[c * 4 + 1] = options.colors[c].g;
  63864. colors[c * 4 + 2] = options.colors[c].b;
  63865. colors[c * 4 + 3] = options.colors[c].a;
  63866. }
  63867. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63868. }
  63869. if (options.uvs) {
  63870. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63871. for (var i = 0; i < options.uvs.length; i++) {
  63872. uvs[i * 2] = options.uvs[i].x;
  63873. uvs[i * 2 + 1] = options.uvs[i].y;
  63874. }
  63875. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63876. }
  63877. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63878. var indices = instance.getIndices();
  63879. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63880. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63881. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63882. if (instance._closePath) {
  63883. var indexFirst = 0;
  63884. var indexLast = 0;
  63885. for (var p = 0; p < pathArray.length; p++) {
  63886. indexFirst = instance._idx[p] * 3;
  63887. if (p + 1 < pathArray.length) {
  63888. indexLast = (instance._idx[p + 1] - 1) * 3;
  63889. }
  63890. else {
  63891. indexLast = normals.length - 3;
  63892. }
  63893. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63894. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63895. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63896. normals[indexLast] = normals[indexFirst];
  63897. normals[indexLast + 1] = normals[indexFirst + 1];
  63898. normals[indexLast + 2] = normals[indexFirst + 2];
  63899. }
  63900. }
  63901. if (!(instance.areNormalsFrozen)) {
  63902. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63903. }
  63904. }
  63905. return instance;
  63906. }
  63907. else { // new ribbon creation
  63908. var ribbon = new BABYLON.Mesh(name, scene);
  63909. ribbon._originalBuilderSideOrientation = sideOrientation;
  63910. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63911. if (closePath) {
  63912. ribbon._idx = vertexData._idx;
  63913. }
  63914. ribbon._closePath = closePath;
  63915. ribbon._closeArray = closeArray;
  63916. vertexData.applyToMesh(ribbon, updatable);
  63917. return ribbon;
  63918. }
  63919. };
  63920. /**
  63921. * Creates a cylinder or a cone mesh
  63922. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63923. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63924. * * 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.
  63925. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63926. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63927. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63928. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63929. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63930. * * 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).
  63931. * * 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
  63932. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63933. * * 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
  63934. * * 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.
  63935. * * If `enclose` is false, a ring surface is one element.
  63936. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63937. * * 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
  63938. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63939. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63940. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63941. * @param name defines the name of the mesh
  63942. * @param options defines the options used to create the mesh
  63943. * @param scene defines the hosting scene
  63944. * @returns the cylinder mesh
  63945. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63946. */
  63947. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63948. var cylinder = new BABYLON.Mesh(name, scene);
  63949. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63950. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63951. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63952. vertexData.applyToMesh(cylinder, options.updatable);
  63953. return cylinder;
  63954. };
  63955. /**
  63956. * Creates a torus mesh
  63957. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63958. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63959. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63960. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63961. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63962. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63963. * @param name defines the name of the mesh
  63964. * @param options defines the options used to create the mesh
  63965. * @param scene defines the hosting scene
  63966. * @returns the torus mesh
  63967. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63968. */
  63969. MeshBuilder.CreateTorus = function (name, options, scene) {
  63970. var torus = new BABYLON.Mesh(name, scene);
  63971. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63972. torus._originalBuilderSideOrientation = options.sideOrientation;
  63973. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63974. vertexData.applyToMesh(torus, options.updatable);
  63975. return torus;
  63976. };
  63977. /**
  63978. * Creates a torus knot mesh
  63979. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63980. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63981. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63982. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63983. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63984. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  63985. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63986. * @param name defines the name of the mesh
  63987. * @param options defines the options used to create the mesh
  63988. * @param scene defines the hosting scene
  63989. * @returns the torus knot mesh
  63990. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63991. */
  63992. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63993. var torusKnot = new BABYLON.Mesh(name, scene);
  63994. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63995. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63996. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63997. vertexData.applyToMesh(torusKnot, options.updatable);
  63998. return torusKnot;
  63999. };
  64000. /**
  64001. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64002. * * 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
  64003. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64004. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64005. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64006. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64007. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64008. * * 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
  64009. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64010. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64011. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64012. * @param name defines the name of the new line system
  64013. * @param options defines the options used to create the line system
  64014. * @param scene defines the hosting scene
  64015. * @returns a new line system mesh
  64016. */
  64017. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64018. var instance = options.instance;
  64019. var lines = options.lines;
  64020. var colors = options.colors;
  64021. if (instance) { // lines update
  64022. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64023. var vertexColor;
  64024. var lineColors;
  64025. if (colors) {
  64026. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64027. }
  64028. var i = 0;
  64029. var c = 0;
  64030. for (var l = 0; l < lines.length; l++) {
  64031. var points = lines[l];
  64032. for (var p = 0; p < points.length; p++) {
  64033. positions[i] = points[p].x;
  64034. positions[i + 1] = points[p].y;
  64035. positions[i + 2] = points[p].z;
  64036. if (colors && vertexColor) {
  64037. lineColors = colors[l];
  64038. vertexColor[c] = lineColors[p].r;
  64039. vertexColor[c + 1] = lineColors[p].g;
  64040. vertexColor[c + 2] = lineColors[p].b;
  64041. vertexColor[c + 3] = lineColors[p].a;
  64042. c += 4;
  64043. }
  64044. i += 3;
  64045. }
  64046. }
  64047. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64048. if (colors && vertexColor) {
  64049. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64050. }
  64051. return instance;
  64052. }
  64053. // line system creation
  64054. var useVertexColor = (colors) ? true : false;
  64055. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64056. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64057. vertexData.applyToMesh(lineSystem, options.updatable);
  64058. return lineSystem;
  64059. };
  64060. /**
  64061. * Creates a line mesh
  64062. * 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
  64063. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64064. * * The parameter `points` is an array successive Vector3
  64065. * * 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
  64066. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64067. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64068. * * When updating an instance, remember that only point positions can change, not the number of points
  64069. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64070. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64071. * @param name defines the name of the new line system
  64072. * @param options defines the options used to create the line system
  64073. * @param scene defines the hosting scene
  64074. * @returns a new line mesh
  64075. */
  64076. MeshBuilder.CreateLines = function (name, options, scene) {
  64077. if (scene === void 0) { scene = null; }
  64078. var colors = (options.colors) ? [options.colors] : null;
  64079. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64080. return lines;
  64081. };
  64082. /**
  64083. * Creates a dashed line mesh
  64084. * * 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
  64085. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64086. * * The parameter `points` is an array successive Vector3
  64087. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64088. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64089. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64090. * * 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
  64091. * * When updating an instance, remember that only point positions can change, not the number of points
  64092. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64093. * @param name defines the name of the mesh
  64094. * @param options defines the options used to create the mesh
  64095. * @param scene defines the hosting scene
  64096. * @returns the dashed line mesh
  64097. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64098. */
  64099. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64100. if (scene === void 0) { scene = null; }
  64101. var points = options.points;
  64102. var instance = options.instance;
  64103. var gapSize = options.gapSize || 1;
  64104. var dashSize = options.dashSize || 3;
  64105. if (instance) { // dashed lines update
  64106. var positionFunction = function (positions) {
  64107. var curvect = BABYLON.Vector3.Zero();
  64108. var nbSeg = positions.length / 6;
  64109. var lg = 0;
  64110. var nb = 0;
  64111. var shft = 0;
  64112. var dashshft = 0;
  64113. var curshft = 0;
  64114. var p = 0;
  64115. var i = 0;
  64116. var j = 0;
  64117. for (i = 0; i < points.length - 1; i++) {
  64118. points[i + 1].subtractToRef(points[i], curvect);
  64119. lg += curvect.length();
  64120. }
  64121. shft = lg / nbSeg;
  64122. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64123. for (i = 0; i < points.length - 1; i++) {
  64124. points[i + 1].subtractToRef(points[i], curvect);
  64125. nb = Math.floor(curvect.length() / shft);
  64126. curvect.normalize();
  64127. j = 0;
  64128. while (j < nb && p < positions.length) {
  64129. curshft = shft * j;
  64130. positions[p] = points[i].x + curshft * curvect.x;
  64131. positions[p + 1] = points[i].y + curshft * curvect.y;
  64132. positions[p + 2] = points[i].z + curshft * curvect.z;
  64133. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64134. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64135. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64136. p += 6;
  64137. j++;
  64138. }
  64139. }
  64140. while (p < positions.length) {
  64141. positions[p] = points[i].x;
  64142. positions[p + 1] = points[i].y;
  64143. positions[p + 2] = points[i].z;
  64144. p += 3;
  64145. }
  64146. };
  64147. instance.updateMeshPositions(positionFunction, false);
  64148. return instance;
  64149. }
  64150. // dashed lines creation
  64151. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64152. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64153. vertexData.applyToMesh(dashedLines, options.updatable);
  64154. dashedLines.dashSize = dashSize;
  64155. dashedLines.gapSize = gapSize;
  64156. return dashedLines;
  64157. };
  64158. /**
  64159. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64160. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  64161. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64162. * * 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.
  64163. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64164. * * 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
  64165. * * 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
  64166. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64167. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64168. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64169. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64170. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64171. * @param name defines the name of the mesh
  64172. * @param options defines the options used to create the mesh
  64173. * @param scene defines the hosting scene
  64174. * @returns the extruded shape mesh
  64175. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64176. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64177. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64178. */
  64179. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64180. if (scene === void 0) { scene = null; }
  64181. var path = options.path;
  64182. var shape = options.shape;
  64183. var scale = options.scale || 1;
  64184. var rotation = options.rotation || 0;
  64185. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64186. var updatable = options.updatable;
  64187. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64188. var instance = options.instance || null;
  64189. var invertUV = options.invertUV || false;
  64190. 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);
  64191. };
  64192. /**
  64193. * Creates an custom extruded shape mesh.
  64194. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64195. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  64196. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64197. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  64198. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64199. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  64200. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64201. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64202. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64203. * * 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
  64204. * * 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
  64205. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64206. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64207. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64208. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64209. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64210. * @param name defines the name of the mesh
  64211. * @param options defines the options used to create the mesh
  64212. * @param scene defines the hosting scene
  64213. * @returns the custom extruded shape mesh
  64214. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64215. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64216. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64217. */
  64218. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64219. var path = options.path;
  64220. var shape = options.shape;
  64221. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64222. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64223. var ribbonCloseArray = options.ribbonCloseArray || false;
  64224. var ribbonClosePath = options.ribbonClosePath || false;
  64225. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64226. var updatable = options.updatable;
  64227. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64228. var instance = options.instance;
  64229. var invertUV = options.invertUV || false;
  64230. 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);
  64231. };
  64232. /**
  64233. * Creates lathe mesh.
  64234. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64235. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  64236. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64237. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64238. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64239. * * 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
  64240. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64241. * * 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
  64242. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64243. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64244. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64245. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64246. * @param name defines the name of the mesh
  64247. * @param options defines the options used to create the mesh
  64248. * @param scene defines the hosting scene
  64249. * @returns the lathe mesh
  64250. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64251. */
  64252. MeshBuilder.CreateLathe = function (name, options, scene) {
  64253. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64254. var closed = (options.closed === undefined) ? true : options.closed;
  64255. var shape = options.shape;
  64256. var radius = options.radius || 1;
  64257. var tessellation = options.tessellation || 64;
  64258. var clip = options.clip || 0;
  64259. var updatable = options.updatable;
  64260. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64261. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64262. var pi2 = Math.PI * 2;
  64263. var paths = new Array();
  64264. var invertUV = options.invertUV || false;
  64265. var i = 0;
  64266. var p = 0;
  64267. var step = pi2 / tessellation * arc;
  64268. var rotated;
  64269. var path = new Array();
  64270. for (i = 0; i <= tessellation - clip; i++) {
  64271. var path = [];
  64272. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64273. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64274. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64275. }
  64276. for (p = 0; p < shape.length; p++) {
  64277. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64278. path.push(rotated);
  64279. }
  64280. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64281. 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));
  64282. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64283. }
  64284. paths.push(path);
  64285. }
  64286. // lathe ribbon
  64287. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64288. return lathe;
  64289. };
  64290. /**
  64291. * Creates a plane mesh
  64292. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64293. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64294. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64295. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64296. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64297. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64298. * @param name defines the name of the mesh
  64299. * @param options defines the options used to create the mesh
  64300. * @param scene defines the hosting scene
  64301. * @returns the plane mesh
  64302. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64303. */
  64304. MeshBuilder.CreatePlane = function (name, options, scene) {
  64305. var plane = new BABYLON.Mesh(name, scene);
  64306. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64307. plane._originalBuilderSideOrientation = options.sideOrientation;
  64308. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64309. vertexData.applyToMesh(plane, options.updatable);
  64310. if (options.sourcePlane) {
  64311. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64312. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64313. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64314. plane.rotate(vectorProduct, product);
  64315. }
  64316. return plane;
  64317. };
  64318. /**
  64319. * Creates a ground mesh
  64320. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64321. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64322. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64323. * @param name defines the name of the mesh
  64324. * @param options defines the options used to create the mesh
  64325. * @param scene defines the hosting scene
  64326. * @returns the ground mesh
  64327. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64328. */
  64329. MeshBuilder.CreateGround = function (name, options, scene) {
  64330. var ground = new BABYLON.GroundMesh(name, scene);
  64331. ground._setReady(false);
  64332. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64333. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64334. ground._width = options.width || 1;
  64335. ground._height = options.height || 1;
  64336. ground._maxX = ground._width / 2;
  64337. ground._maxZ = ground._height / 2;
  64338. ground._minX = -ground._maxX;
  64339. ground._minZ = -ground._maxZ;
  64340. var vertexData = BABYLON.VertexData.CreateGround(options);
  64341. vertexData.applyToMesh(ground, options.updatable);
  64342. ground._setReady(true);
  64343. return ground;
  64344. };
  64345. /**
  64346. * Creates a tiled ground mesh
  64347. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64348. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64349. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  64350. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  64351. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64352. * @param name defines the name of the mesh
  64353. * @param options defines the options used to create the mesh
  64354. * @param scene defines the hosting scene
  64355. * @returns the tiled ground mesh
  64356. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64357. */
  64358. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64359. var tiledGround = new BABYLON.Mesh(name, scene);
  64360. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64361. vertexData.applyToMesh(tiledGround, options.updatable);
  64362. return tiledGround;
  64363. };
  64364. /**
  64365. * Creates a ground mesh from a height map
  64366. * * The parameter `url` sets the URL of the height map image resource.
  64367. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64368. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64369. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64370. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64371. * * 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.
  64372. * * 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).
  64373. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64374. * @param name defines the name of the mesh
  64375. * @param url defines the url to the height map
  64376. * @param options defines the options used to create the mesh
  64377. * @param scene defines the hosting scene
  64378. * @returns the ground mesh
  64379. * @see http://doc.babylonjs.com/babylon101/height_map
  64380. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64381. */
  64382. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64383. var width = options.width || 10.0;
  64384. var height = options.height || 10.0;
  64385. var subdivisions = options.subdivisions || 1 | 0;
  64386. var minHeight = options.minHeight || 0.0;
  64387. var maxHeight = options.maxHeight || 1.0;
  64388. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64389. var updatable = options.updatable;
  64390. var onReady = options.onReady;
  64391. var ground = new BABYLON.GroundMesh(name, scene);
  64392. ground._subdivisionsX = subdivisions;
  64393. ground._subdivisionsY = subdivisions;
  64394. ground._width = width;
  64395. ground._height = height;
  64396. ground._maxX = ground._width / 2.0;
  64397. ground._maxZ = ground._height / 2.0;
  64398. ground._minX = -ground._maxX;
  64399. ground._minZ = -ground._maxZ;
  64400. ground._setReady(false);
  64401. var onload = function (img) {
  64402. // Getting height map data
  64403. var canvas = document.createElement("canvas");
  64404. var context = canvas.getContext("2d");
  64405. if (!context) {
  64406. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64407. }
  64408. if (scene.isDisposed) {
  64409. return;
  64410. }
  64411. var bufferWidth = img.width;
  64412. var bufferHeight = img.height;
  64413. canvas.width = bufferWidth;
  64414. canvas.height = bufferHeight;
  64415. context.drawImage(img, 0, 0);
  64416. // Create VertexData from map data
  64417. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64418. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64419. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64420. width: width, height: height,
  64421. subdivisions: subdivisions,
  64422. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64423. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64424. });
  64425. vertexData.applyToMesh(ground, updatable);
  64426. //execute ready callback, if set
  64427. if (onReady) {
  64428. onReady(ground);
  64429. }
  64430. ground._setReady(true);
  64431. };
  64432. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64433. return ground;
  64434. };
  64435. /**
  64436. * Creates a polygon mesh
  64437. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64438. * * 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
  64439. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64440. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64441. * * 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)
  64442. * * Remember you can only change the shape positions, not their number when updating a polygon
  64443. * @param name defines the name of the mesh
  64444. * @param options defines the options used to create the mesh
  64445. * @param scene defines the hosting scene
  64446. * @returns the polygon mesh
  64447. */
  64448. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64449. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64450. var shape = options.shape;
  64451. var holes = options.holes || [];
  64452. var depth = options.depth || 0;
  64453. var contours = [];
  64454. var hole = [];
  64455. for (var i = 0; i < shape.length; i++) {
  64456. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64457. }
  64458. var epsilon = 0.00000001;
  64459. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64460. contours.pop();
  64461. }
  64462. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64463. for (var hNb = 0; hNb < holes.length; hNb++) {
  64464. hole = [];
  64465. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64466. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64467. }
  64468. polygonTriangulation.addHole(hole);
  64469. }
  64470. var polygon = polygonTriangulation.build(options.updatable, depth);
  64471. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64472. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64473. vertexData.applyToMesh(polygon, options.updatable);
  64474. return polygon;
  64475. };
  64476. ;
  64477. /**
  64478. * Creates an extruded polygon mesh, with depth in the Y direction.
  64479. * * 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)
  64480. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64481. * @param name defines the name of the mesh
  64482. * @param options defines the options used to create the mesh
  64483. * @param scene defines the hosting scene
  64484. * @returns the polygon mesh
  64485. */
  64486. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64487. return MeshBuilder.CreatePolygon(name, options, scene);
  64488. };
  64489. ;
  64490. /**
  64491. * Creates a tube mesh.
  64492. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64493. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64494. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64495. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64496. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64497. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  64498. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64499. * * 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
  64500. * * 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
  64501. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64502. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64503. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64504. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64505. * @param name defines the name of the mesh
  64506. * @param options defines the options used to create the mesh
  64507. * @param scene defines the hosting scene
  64508. * @returns the tube mesh
  64509. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64510. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64511. */
  64512. MeshBuilder.CreateTube = function (name, options, scene) {
  64513. var path = options.path;
  64514. var instance = options.instance;
  64515. var radius = 1.0;
  64516. if (instance) {
  64517. radius = instance.radius;
  64518. }
  64519. if (options.radius !== undefined) {
  64520. radius = options.radius;
  64521. }
  64522. ;
  64523. var tessellation = options.tessellation || 64 | 0;
  64524. var radiusFunction = options.radiusFunction || null;
  64525. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64526. var invertUV = options.invertUV || false;
  64527. var updatable = options.updatable;
  64528. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64529. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64530. // tube geometry
  64531. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64532. var tangents = path3D.getTangents();
  64533. var normals = path3D.getNormals();
  64534. var distances = path3D.getDistances();
  64535. var pi2 = Math.PI * 2;
  64536. var step = pi2 / tessellation * arc;
  64537. var returnRadius = function () { return radius; };
  64538. var radiusFunctionFinal = radiusFunction || returnRadius;
  64539. var circlePath;
  64540. var rad;
  64541. var normal;
  64542. var rotated;
  64543. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64544. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64545. for (var i = 0; i < path.length; i++) {
  64546. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64547. circlePath = Array(); // current circle array
  64548. normal = normals[i]; // current normal
  64549. for (var t = 0; t < tessellation; t++) {
  64550. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64551. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64552. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64553. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64554. circlePath[t] = rotated;
  64555. }
  64556. circlePaths[index] = circlePath;
  64557. index++;
  64558. }
  64559. // cap
  64560. var capPath = function (nbPoints, pathIndex) {
  64561. var pointCap = Array();
  64562. for (var i = 0; i < nbPoints; i++) {
  64563. pointCap.push(path[pathIndex]);
  64564. }
  64565. return pointCap;
  64566. };
  64567. switch (cap) {
  64568. case BABYLON.Mesh.NO_CAP:
  64569. break;
  64570. case BABYLON.Mesh.CAP_START:
  64571. circlePaths[0] = capPath(tessellation, 0);
  64572. circlePaths[1] = circlePaths[2].slice(0);
  64573. break;
  64574. case BABYLON.Mesh.CAP_END:
  64575. circlePaths[index] = circlePaths[index - 1].slice(0);
  64576. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64577. break;
  64578. case BABYLON.Mesh.CAP_ALL:
  64579. circlePaths[0] = capPath(tessellation, 0);
  64580. circlePaths[1] = circlePaths[2].slice(0);
  64581. circlePaths[index] = circlePaths[index - 1].slice(0);
  64582. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64583. break;
  64584. default:
  64585. break;
  64586. }
  64587. return circlePaths;
  64588. };
  64589. var path3D;
  64590. var pathArray;
  64591. if (instance) { // tube update
  64592. var arc = options.arc || instance.arc;
  64593. path3D = (instance.path3D).update(path);
  64594. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64595. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64596. instance.path3D = path3D;
  64597. instance.pathArray = pathArray;
  64598. instance.arc = arc;
  64599. instance.radius = radius;
  64600. return instance;
  64601. }
  64602. // tube creation
  64603. path3D = new BABYLON.Path3D(path);
  64604. var newPathArray = new Array();
  64605. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64606. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64607. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64608. tube.pathArray = pathArray;
  64609. tube.path3D = path3D;
  64610. tube.tessellation = tessellation;
  64611. tube.cap = cap;
  64612. tube.arc = options.arc;
  64613. tube.radius = radius;
  64614. return tube;
  64615. };
  64616. /**
  64617. * Creates a polyhedron mesh
  64618. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  64619. * * The parameter `size` (positive float, default 1) sets the polygon size
  64620. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64621. * * 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`
  64622. * * 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
  64623. * * 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)`)
  64624. * * 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
  64625. * * 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
  64626. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64627. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64628. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64629. * @param name defines the name of the mesh
  64630. * @param options defines the options used to create the mesh
  64631. * @param scene defines the hosting scene
  64632. * @returns the polyhedron mesh
  64633. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64634. */
  64635. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64636. var polyhedron = new BABYLON.Mesh(name, scene);
  64637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64638. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64639. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64640. vertexData.applyToMesh(polyhedron, options.updatable);
  64641. return polyhedron;
  64642. };
  64643. /**
  64644. * Creates a decal mesh.
  64645. * 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
  64646. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64647. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64648. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64649. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64650. * @param name defines the name of the mesh
  64651. * @param sourceMesh defines the mesh where the decal must be applied
  64652. * @param options defines the options used to create the mesh
  64653. * @param scene defines the hosting scene
  64654. * @returns the decal mesh
  64655. * @see http://doc.babylonjs.com/how_to/decals
  64656. */
  64657. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64658. var indices = sourceMesh.getIndices();
  64659. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64660. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64661. var position = options.position || BABYLON.Vector3.Zero();
  64662. var normal = options.normal || BABYLON.Vector3.Up();
  64663. var size = options.size || BABYLON.Vector3.One();
  64664. var angle = options.angle || 0;
  64665. // Getting correct rotation
  64666. if (!normal) {
  64667. var target = new BABYLON.Vector3(0, 0, 1);
  64668. var camera = sourceMesh.getScene().activeCamera;
  64669. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64670. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64671. }
  64672. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64673. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64674. var pitch = Math.atan2(normal.y, len);
  64675. // Matrix
  64676. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64677. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64678. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64679. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64680. var vertexData = new BABYLON.VertexData();
  64681. vertexData.indices = [];
  64682. vertexData.positions = [];
  64683. vertexData.normals = [];
  64684. vertexData.uvs = [];
  64685. var currentVertexDataIndex = 0;
  64686. var extractDecalVector3 = function (indexId) {
  64687. var result = new BABYLON.PositionNormalVertex();
  64688. if (!indices || !positions || !normals) {
  64689. return result;
  64690. }
  64691. var vertexId = indices[indexId];
  64692. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64693. // Send vector to decal local world
  64694. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64695. // Get normal
  64696. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64697. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64698. return result;
  64699. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64700. var clip = function (vertices, axis) {
  64701. if (vertices.length === 0) {
  64702. return vertices;
  64703. }
  64704. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64705. var clipVertices = function (v0, v1) {
  64706. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64707. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64708. };
  64709. var result = new Array();
  64710. for (var index = 0; index < vertices.length; index += 3) {
  64711. var v1Out;
  64712. var v2Out;
  64713. var v3Out;
  64714. var total = 0;
  64715. var nV1 = null;
  64716. var nV2 = null;
  64717. var nV3 = null;
  64718. var nV4 = null;
  64719. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64720. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64721. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64722. v1Out = d1 > 0;
  64723. v2Out = d2 > 0;
  64724. v3Out = d3 > 0;
  64725. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64726. switch (total) {
  64727. case 0:
  64728. result.push(vertices[index]);
  64729. result.push(vertices[index + 1]);
  64730. result.push(vertices[index + 2]);
  64731. break;
  64732. case 1:
  64733. if (v1Out) {
  64734. nV1 = vertices[index + 1];
  64735. nV2 = vertices[index + 2];
  64736. nV3 = clipVertices(vertices[index], nV1);
  64737. nV4 = clipVertices(vertices[index], nV2);
  64738. }
  64739. if (v2Out) {
  64740. nV1 = vertices[index];
  64741. nV2 = vertices[index + 2];
  64742. nV3 = clipVertices(vertices[index + 1], nV1);
  64743. nV4 = clipVertices(vertices[index + 1], nV2);
  64744. result.push(nV3);
  64745. result.push(nV2.clone());
  64746. result.push(nV1.clone());
  64747. result.push(nV2.clone());
  64748. result.push(nV3.clone());
  64749. result.push(nV4);
  64750. break;
  64751. }
  64752. if (v3Out) {
  64753. nV1 = vertices[index];
  64754. nV2 = vertices[index + 1];
  64755. nV3 = clipVertices(vertices[index + 2], nV1);
  64756. nV4 = clipVertices(vertices[index + 2], nV2);
  64757. }
  64758. if (nV1 && nV2 && nV3 && nV4) {
  64759. result.push(nV1.clone());
  64760. result.push(nV2.clone());
  64761. result.push(nV3);
  64762. result.push(nV4);
  64763. result.push(nV3.clone());
  64764. result.push(nV2.clone());
  64765. }
  64766. break;
  64767. case 2:
  64768. if (!v1Out) {
  64769. nV1 = vertices[index].clone();
  64770. nV2 = clipVertices(nV1, vertices[index + 1]);
  64771. nV3 = clipVertices(nV1, vertices[index + 2]);
  64772. result.push(nV1);
  64773. result.push(nV2);
  64774. result.push(nV3);
  64775. }
  64776. if (!v2Out) {
  64777. nV1 = vertices[index + 1].clone();
  64778. nV2 = clipVertices(nV1, vertices[index + 2]);
  64779. nV3 = clipVertices(nV1, vertices[index]);
  64780. result.push(nV1);
  64781. result.push(nV2);
  64782. result.push(nV3);
  64783. }
  64784. if (!v3Out) {
  64785. nV1 = vertices[index + 2].clone();
  64786. nV2 = clipVertices(nV1, vertices[index]);
  64787. nV3 = clipVertices(nV1, vertices[index + 1]);
  64788. result.push(nV1);
  64789. result.push(nV2);
  64790. result.push(nV3);
  64791. }
  64792. break;
  64793. case 3:
  64794. break;
  64795. }
  64796. }
  64797. return result;
  64798. };
  64799. for (var index = 0; index < indices.length; index += 3) {
  64800. var faceVertices = new Array();
  64801. faceVertices.push(extractDecalVector3(index));
  64802. faceVertices.push(extractDecalVector3(index + 1));
  64803. faceVertices.push(extractDecalVector3(index + 2));
  64804. // Clip
  64805. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64806. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64807. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64808. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64809. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64810. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64811. if (faceVertices.length === 0) {
  64812. continue;
  64813. }
  64814. // Add UVs and get back to world
  64815. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64816. var vertex = faceVertices[vIndex];
  64817. //TODO check for Int32Array | Uint32Array | Uint16Array
  64818. vertexData.indices.push(currentVertexDataIndex);
  64819. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64820. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64821. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64822. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64823. currentVertexDataIndex++;
  64824. }
  64825. }
  64826. // Return mesh
  64827. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64828. vertexData.applyToMesh(decal);
  64829. decal.position = position.clone();
  64830. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64831. return decal;
  64832. };
  64833. // Privates
  64834. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64835. // extrusion geometry
  64836. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64837. var tangents = path3D.getTangents();
  64838. var normals = path3D.getNormals();
  64839. var binormals = path3D.getBinormals();
  64840. var distances = path3D.getDistances();
  64841. var angle = 0;
  64842. var returnScale = function () { return scale !== null ? scale : 1; };
  64843. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64844. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64845. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64846. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64847. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64848. for (var i = 0; i < curve.length; i++) {
  64849. var shapePath = new Array();
  64850. var angleStep = rotate(i, distances[i]);
  64851. var scaleRatio = scl(i, distances[i]);
  64852. for (var p = 0; p < shape.length; p++) {
  64853. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64854. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64855. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64856. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64857. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64858. shapePath[p] = rotated;
  64859. }
  64860. shapePaths[index] = shapePath;
  64861. angle += angleStep;
  64862. index++;
  64863. }
  64864. // cap
  64865. var capPath = function (shapePath) {
  64866. var pointCap = Array();
  64867. var barycenter = BABYLON.Vector3.Zero();
  64868. var i;
  64869. for (i = 0; i < shapePath.length; i++) {
  64870. barycenter.addInPlace(shapePath[i]);
  64871. }
  64872. barycenter.scaleInPlace(1.0 / shapePath.length);
  64873. for (i = 0; i < shapePath.length; i++) {
  64874. pointCap.push(barycenter);
  64875. }
  64876. return pointCap;
  64877. };
  64878. switch (cap) {
  64879. case BABYLON.Mesh.NO_CAP:
  64880. break;
  64881. case BABYLON.Mesh.CAP_START:
  64882. shapePaths[0] = capPath(shapePaths[2]);
  64883. shapePaths[1] = shapePaths[2];
  64884. break;
  64885. case BABYLON.Mesh.CAP_END:
  64886. shapePaths[index] = shapePaths[index - 1];
  64887. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64888. break;
  64889. case BABYLON.Mesh.CAP_ALL:
  64890. shapePaths[0] = capPath(shapePaths[2]);
  64891. shapePaths[1] = shapePaths[2];
  64892. shapePaths[index] = shapePaths[index - 1];
  64893. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64894. break;
  64895. default:
  64896. break;
  64897. }
  64898. return shapePaths;
  64899. };
  64900. var path3D;
  64901. var pathArray;
  64902. if (instance) { // instance update
  64903. path3D = (instance.path3D).update(curve);
  64904. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64905. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64906. return instance;
  64907. }
  64908. // extruded shape creation
  64909. path3D = new BABYLON.Path3D(curve);
  64910. var newShapePaths = new Array();
  64911. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64912. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64913. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64914. extrudedGeneric.pathArray = pathArray;
  64915. extrudedGeneric.path3D = path3D;
  64916. extrudedGeneric.cap = cap;
  64917. return extrudedGeneric;
  64918. };
  64919. return MeshBuilder;
  64920. }());
  64921. BABYLON.MeshBuilder = MeshBuilder;
  64922. })(BABYLON || (BABYLON = {}));
  64923. //# sourceMappingURL=babylon.meshBuilder.js.map
  64924. var BABYLON;
  64925. (function (BABYLON) {
  64926. /**
  64927. * Draco compression (https://google.github.io/draco/)
  64928. *
  64929. * This class wraps the Draco module.
  64930. *
  64931. * **Encoder**
  64932. *
  64933. * The encoder is not currently implemented.
  64934. *
  64935. * **Decoder**
  64936. *
  64937. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64938. *
  64939. * To update the configuration, use the following code:
  64940. * ```javascript
  64941. * BABYLON.DracoCompression.Configuration = {
  64942. * decoder: {
  64943. * wasmUrl: "<url to the WebAssembly library>",
  64944. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64945. * fallbackUrl: "<url to the fallback JavaScript library>",
  64946. * }
  64947. * };
  64948. * ```
  64949. *
  64950. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  64951. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64952. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64953. *
  64954. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64955. * ```javascript
  64956. * var dracoCompression = new BABYLON.DracoCompression();
  64957. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64958. * [BABYLON.VertexBuffer.PositionKind]: 0
  64959. * });
  64960. * ```
  64961. *
  64962. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64963. */
  64964. var DracoCompression = /** @class */ (function () {
  64965. /**
  64966. * Constructor
  64967. */
  64968. function DracoCompression() {
  64969. }
  64970. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64971. /**
  64972. * Returns true if the decoder is available.
  64973. */
  64974. get: function () {
  64975. if (typeof DracoDecoderModule !== "undefined") {
  64976. return true;
  64977. }
  64978. var decoder = DracoCompression.Configuration.decoder;
  64979. if (decoder) {
  64980. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64981. return true;
  64982. }
  64983. if (decoder.fallbackUrl) {
  64984. return true;
  64985. }
  64986. }
  64987. return false;
  64988. },
  64989. enumerable: true,
  64990. configurable: true
  64991. });
  64992. /**
  64993. * Stop all async operations and release resources.
  64994. */
  64995. DracoCompression.prototype.dispose = function () {
  64996. };
  64997. /**
  64998. * Decode Draco compressed mesh data to vertex data.
  64999. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65000. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65001. * @returns A promise that resolves with the decoded vertex data
  65002. */
  65003. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65004. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65005. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65006. var module = wrappedModule.module;
  65007. var vertexData = new BABYLON.VertexData();
  65008. var buffer = new module.DecoderBuffer();
  65009. buffer.Init(dataView, dataView.byteLength);
  65010. var decoder = new module.Decoder();
  65011. var geometry;
  65012. var status;
  65013. try {
  65014. var type = decoder.GetEncodedGeometryType(buffer);
  65015. switch (type) {
  65016. case module.TRIANGULAR_MESH:
  65017. geometry = new module.Mesh();
  65018. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65019. break;
  65020. case module.POINT_CLOUD:
  65021. geometry = new module.PointCloud();
  65022. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65023. break;
  65024. default:
  65025. throw new Error("Invalid geometry type " + type);
  65026. }
  65027. if (!status.ok() || !geometry.ptr) {
  65028. throw new Error(status.error_msg());
  65029. }
  65030. var numPoints = geometry.num_points();
  65031. if (type === module.TRIANGULAR_MESH) {
  65032. var numFaces = geometry.num_faces();
  65033. var faceIndices = new module.DracoInt32Array();
  65034. try {
  65035. var indices = new Uint32Array(numFaces * 3);
  65036. for (var i = 0; i < numFaces; i++) {
  65037. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65038. var offset = i * 3;
  65039. indices[offset + 0] = faceIndices.GetValue(0);
  65040. indices[offset + 1] = faceIndices.GetValue(1);
  65041. indices[offset + 2] = faceIndices.GetValue(2);
  65042. }
  65043. vertexData.indices = indices;
  65044. }
  65045. finally {
  65046. module.destroy(faceIndices);
  65047. }
  65048. }
  65049. for (var kind in attributes) {
  65050. var uniqueId = attributes[kind];
  65051. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65052. var dracoData = new module.DracoFloat32Array();
  65053. try {
  65054. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65055. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65056. for (var i = 0; i < babylonData.length; i++) {
  65057. babylonData[i] = dracoData.GetValue(i);
  65058. }
  65059. vertexData.set(babylonData, kind);
  65060. }
  65061. finally {
  65062. module.destroy(dracoData);
  65063. }
  65064. }
  65065. }
  65066. finally {
  65067. if (geometry) {
  65068. module.destroy(geometry);
  65069. }
  65070. module.destroy(decoder);
  65071. module.destroy(buffer);
  65072. }
  65073. return vertexData;
  65074. });
  65075. };
  65076. DracoCompression._GetDecoderModule = function () {
  65077. if (!DracoCompression._DecoderModulePromise) {
  65078. var promise = null;
  65079. var config_1 = {};
  65080. if (typeof DracoDecoderModule !== "undefined") {
  65081. promise = Promise.resolve();
  65082. }
  65083. else {
  65084. var decoder = DracoCompression.Configuration.decoder;
  65085. if (decoder) {
  65086. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65087. promise = Promise.all([
  65088. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65089. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65090. config_1.wasmBinary = data;
  65091. })
  65092. ]);
  65093. }
  65094. else if (decoder.fallbackUrl) {
  65095. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65096. }
  65097. }
  65098. }
  65099. if (!promise) {
  65100. throw new Error("Draco decoder module is not available");
  65101. }
  65102. DracoCompression._DecoderModulePromise = promise.then(function () {
  65103. return new Promise(function (resolve) {
  65104. config_1.onModuleLoaded = function (decoderModule) {
  65105. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65106. resolve({ module: decoderModule });
  65107. };
  65108. DracoDecoderModule(config_1);
  65109. });
  65110. });
  65111. }
  65112. return DracoCompression._DecoderModulePromise;
  65113. };
  65114. DracoCompression._LoadScriptAsync = function (url) {
  65115. return new Promise(function (resolve, reject) {
  65116. BABYLON.Tools.LoadScript(url, function () {
  65117. resolve();
  65118. }, function (message) {
  65119. reject(new Error(message));
  65120. });
  65121. });
  65122. };
  65123. DracoCompression._LoadFileAsync = function (url) {
  65124. return new Promise(function (resolve, reject) {
  65125. BABYLON.Tools.LoadFile(url, function (data) {
  65126. resolve(data);
  65127. }, undefined, undefined, true, function (request, exception) {
  65128. reject(exception);
  65129. });
  65130. });
  65131. };
  65132. /**
  65133. * The configuration. Defaults to the following urls:
  65134. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65135. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65136. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65137. */
  65138. DracoCompression.Configuration = {
  65139. decoder: {
  65140. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65141. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65142. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65143. }
  65144. };
  65145. return DracoCompression;
  65146. }());
  65147. BABYLON.DracoCompression = DracoCompression;
  65148. })(BABYLON || (BABYLON = {}));
  65149. //# sourceMappingURL=babylon.dracoCompression.js.map
  65150. var BABYLON;
  65151. (function (BABYLON) {
  65152. var AudioEngine = /** @class */ (function () {
  65153. function AudioEngine() {
  65154. this._audioContext = null;
  65155. this._audioContextInitialized = false;
  65156. this.canUseWebAudio = false;
  65157. this.WarnedWebAudioUnsupported = false;
  65158. this.unlocked = false;
  65159. this.isMP3supported = false;
  65160. this.isOGGsupported = false;
  65161. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65162. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65163. this.canUseWebAudio = true;
  65164. }
  65165. var audioElem = document.createElement('audio');
  65166. try {
  65167. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65168. this.isMP3supported = true;
  65169. }
  65170. }
  65171. catch (e) {
  65172. // protect error during capability check.
  65173. }
  65174. try {
  65175. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65176. this.isOGGsupported = true;
  65177. }
  65178. }
  65179. catch (e) {
  65180. // protect error during capability check.
  65181. }
  65182. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65183. this._unlockiOSaudio();
  65184. }
  65185. else {
  65186. this.unlocked = true;
  65187. }
  65188. }
  65189. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65190. get: function () {
  65191. if (!this._audioContextInitialized) {
  65192. this._initializeAudioContext();
  65193. }
  65194. return this._audioContext;
  65195. },
  65196. enumerable: true,
  65197. configurable: true
  65198. });
  65199. AudioEngine.prototype._unlockiOSaudio = function () {
  65200. var _this = this;
  65201. var unlockaudio = function () {
  65202. if (!_this.audioContext) {
  65203. return;
  65204. }
  65205. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65206. var source = _this.audioContext.createBufferSource();
  65207. source.buffer = buffer;
  65208. source.connect(_this.audioContext.destination);
  65209. source.start(0);
  65210. setTimeout(function () {
  65211. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65212. _this.unlocked = true;
  65213. window.removeEventListener('touchend', unlockaudio, false);
  65214. if (_this.onAudioUnlocked) {
  65215. _this.onAudioUnlocked();
  65216. }
  65217. }
  65218. }, 0);
  65219. };
  65220. window.addEventListener('touchend', unlockaudio, false);
  65221. };
  65222. AudioEngine.prototype._initializeAudioContext = function () {
  65223. try {
  65224. if (this.canUseWebAudio) {
  65225. this._audioContext = new AudioContext();
  65226. // create a global volume gain node
  65227. this.masterGain = this._audioContext.createGain();
  65228. this.masterGain.gain.value = 1;
  65229. this.masterGain.connect(this._audioContext.destination);
  65230. this._audioContextInitialized = true;
  65231. }
  65232. }
  65233. catch (e) {
  65234. this.canUseWebAudio = false;
  65235. BABYLON.Tools.Error("Web Audio: " + e.message);
  65236. }
  65237. };
  65238. AudioEngine.prototype.dispose = function () {
  65239. if (this.canUseWebAudio && this._audioContextInitialized) {
  65240. if (this._connectedAnalyser && this._audioContext) {
  65241. this._connectedAnalyser.stopDebugCanvas();
  65242. this._connectedAnalyser.dispose();
  65243. this.masterGain.disconnect();
  65244. this.masterGain.connect(this._audioContext.destination);
  65245. this._connectedAnalyser = null;
  65246. }
  65247. this.masterGain.gain.value = 1;
  65248. }
  65249. this.WarnedWebAudioUnsupported = false;
  65250. };
  65251. AudioEngine.prototype.getGlobalVolume = function () {
  65252. if (this.canUseWebAudio && this._audioContextInitialized) {
  65253. return this.masterGain.gain.value;
  65254. }
  65255. else {
  65256. return -1;
  65257. }
  65258. };
  65259. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65260. if (this.canUseWebAudio && this._audioContextInitialized) {
  65261. this.masterGain.gain.value = newVolume;
  65262. }
  65263. };
  65264. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65265. if (this._connectedAnalyser) {
  65266. this._connectedAnalyser.stopDebugCanvas();
  65267. }
  65268. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65269. this._connectedAnalyser = analyser;
  65270. this.masterGain.disconnect();
  65271. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65272. }
  65273. };
  65274. return AudioEngine;
  65275. }());
  65276. BABYLON.AudioEngine = AudioEngine;
  65277. })(BABYLON || (BABYLON = {}));
  65278. //# sourceMappingURL=babylon.audioEngine.js.map
  65279. var BABYLON;
  65280. (function (BABYLON) {
  65281. var Sound = /** @class */ (function () {
  65282. /**
  65283. * Create a sound and attach it to a scene
  65284. * @param name Name of your sound
  65285. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65286. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65287. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65288. */
  65289. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65290. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65291. var _this = this;
  65292. this.autoplay = false;
  65293. this.loop = false;
  65294. this.useCustomAttenuation = false;
  65295. this.spatialSound = false;
  65296. this.refDistance = 1;
  65297. this.rolloffFactor = 1;
  65298. this.maxDistance = 100;
  65299. this.distanceModel = "linear";
  65300. this._panningModel = "equalpower";
  65301. /**
  65302. * Observable event when the current playing sound finishes.
  65303. */
  65304. this.onEndedObservable = new BABYLON.Observable();
  65305. this._playbackRate = 1;
  65306. this._streaming = false;
  65307. this._startTime = 0;
  65308. this._startOffset = 0;
  65309. this._position = BABYLON.Vector3.Zero();
  65310. /** @hidden */
  65311. this._positionInEmitterSpace = false;
  65312. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65313. this._volume = 1;
  65314. this._isReadyToPlay = false;
  65315. this.isPlaying = false;
  65316. this.isPaused = false;
  65317. this._isDirectional = false;
  65318. // Used if you'd like to create a directional sound.
  65319. // If not set, the sound will be omnidirectional
  65320. this._coneInnerAngle = 360;
  65321. this._coneOuterAngle = 360;
  65322. this._coneOuterGain = 0;
  65323. this._isOutputConnected = false;
  65324. this._urlType = "Unknown";
  65325. this.name = name;
  65326. this._scene = scene;
  65327. this._readyToPlayCallback = readyToPlayCallback;
  65328. // Default custom attenuation function is a linear attenuation
  65329. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65330. if (currentDistance < maxDistance) {
  65331. return currentVolume * (1 - currentDistance / maxDistance);
  65332. }
  65333. else {
  65334. return 0;
  65335. }
  65336. };
  65337. if (options) {
  65338. this.autoplay = options.autoplay || false;
  65339. this.loop = options.loop || false;
  65340. // if volume === 0, we need another way to check this option
  65341. if (options.volume !== undefined) {
  65342. this._volume = options.volume;
  65343. }
  65344. this.spatialSound = options.spatialSound || false;
  65345. this.maxDistance = options.maxDistance || 100;
  65346. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65347. this.rolloffFactor = options.rolloffFactor || 1;
  65348. this.refDistance = options.refDistance || 1;
  65349. this.distanceModel = options.distanceModel || "linear";
  65350. this._playbackRate = options.playbackRate || 1;
  65351. this._streaming = options.streaming || false;
  65352. }
  65353. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65354. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65355. this._soundGain.gain.value = this._volume;
  65356. this._inputAudioNode = this._soundGain;
  65357. this._outputAudioNode = this._soundGain;
  65358. if (this.spatialSound) {
  65359. this._createSpatialParameters();
  65360. }
  65361. this._scene.mainSoundTrack.AddSound(this);
  65362. var validParameter = true;
  65363. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65364. if (urlOrArrayBuffer) {
  65365. try {
  65366. if (typeof (urlOrArrayBuffer) === "string") {
  65367. this._urlType = "String";
  65368. }
  65369. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65370. this._urlType = "ArrayBuffer";
  65371. }
  65372. else if (urlOrArrayBuffer instanceof MediaStream) {
  65373. this._urlType = "MediaStream";
  65374. }
  65375. else if (Array.isArray(urlOrArrayBuffer)) {
  65376. this._urlType = "Array";
  65377. }
  65378. var urls = [];
  65379. var codecSupportedFound = false;
  65380. switch (this._urlType) {
  65381. case "MediaStream":
  65382. this._streaming = true;
  65383. this._isReadyToPlay = true;
  65384. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65385. if (this.autoplay) {
  65386. this.play();
  65387. }
  65388. if (this._readyToPlayCallback) {
  65389. this._readyToPlayCallback();
  65390. }
  65391. break;
  65392. case "ArrayBuffer":
  65393. if (urlOrArrayBuffer.byteLength > 0) {
  65394. codecSupportedFound = true;
  65395. this._soundLoaded(urlOrArrayBuffer);
  65396. }
  65397. break;
  65398. case "String":
  65399. urls.push(urlOrArrayBuffer);
  65400. case "Array":
  65401. if (urls.length === 0)
  65402. urls = urlOrArrayBuffer;
  65403. // If we found a supported format, we load it immediately and stop the loop
  65404. for (var i = 0; i < urls.length; i++) {
  65405. var url = urls[i];
  65406. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65407. codecSupportedFound = true;
  65408. }
  65409. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65410. codecSupportedFound = true;
  65411. }
  65412. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65413. codecSupportedFound = true;
  65414. }
  65415. if (url.indexOf("blob:") !== -1) {
  65416. codecSupportedFound = true;
  65417. }
  65418. if (codecSupportedFound) {
  65419. // Loading sound using XHR2
  65420. if (!this._streaming) {
  65421. this._scene._loadFile(url, function (data) {
  65422. _this._soundLoaded(data);
  65423. }, undefined, true, true, function (exception) {
  65424. if (exception) {
  65425. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65426. }
  65427. BABYLON.Tools.Error("Sound creation aborted.");
  65428. _this._scene.mainSoundTrack.RemoveSound(_this);
  65429. });
  65430. }
  65431. // Streaming sound using HTML5 Audio tag
  65432. else {
  65433. this._htmlAudioElement = new Audio(url);
  65434. this._htmlAudioElement.controls = false;
  65435. this._htmlAudioElement.loop = this.loop;
  65436. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65437. this._htmlAudioElement.preload = "auto";
  65438. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65439. _this._isReadyToPlay = true;
  65440. if (_this.autoplay) {
  65441. _this.play();
  65442. }
  65443. if (_this._readyToPlayCallback) {
  65444. _this._readyToPlayCallback();
  65445. }
  65446. });
  65447. document.body.appendChild(this._htmlAudioElement);
  65448. }
  65449. break;
  65450. }
  65451. }
  65452. break;
  65453. default:
  65454. validParameter = false;
  65455. break;
  65456. }
  65457. if (!validParameter) {
  65458. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65459. }
  65460. else {
  65461. if (!codecSupportedFound) {
  65462. this._isReadyToPlay = true;
  65463. // Simulating a ready to play event to avoid breaking code path
  65464. if (this._readyToPlayCallback) {
  65465. window.setTimeout(function () {
  65466. if (_this._readyToPlayCallback) {
  65467. _this._readyToPlayCallback();
  65468. }
  65469. }, 1000);
  65470. }
  65471. }
  65472. }
  65473. }
  65474. catch (ex) {
  65475. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65476. this._scene.mainSoundTrack.RemoveSound(this);
  65477. }
  65478. }
  65479. }
  65480. else {
  65481. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65482. this._scene.mainSoundTrack.AddSound(this);
  65483. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65484. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65485. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65486. }
  65487. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65488. if (this._readyToPlayCallback) {
  65489. window.setTimeout(function () {
  65490. if (_this._readyToPlayCallback) {
  65491. _this._readyToPlayCallback();
  65492. }
  65493. }, 1000);
  65494. }
  65495. }
  65496. }
  65497. Sound.prototype.dispose = function () {
  65498. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65499. if (this.isPlaying) {
  65500. this.stop();
  65501. }
  65502. this._isReadyToPlay = false;
  65503. if (this.soundTrackId === -1) {
  65504. this._scene.mainSoundTrack.RemoveSound(this);
  65505. }
  65506. else {
  65507. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65508. }
  65509. if (this._soundGain) {
  65510. this._soundGain.disconnect();
  65511. this._soundGain = null;
  65512. }
  65513. if (this._soundPanner) {
  65514. this._soundPanner.disconnect();
  65515. this._soundPanner = null;
  65516. }
  65517. if (this._soundSource) {
  65518. this._soundSource.disconnect();
  65519. this._soundSource = null;
  65520. }
  65521. this._audioBuffer = null;
  65522. if (this._htmlAudioElement) {
  65523. this._htmlAudioElement.pause();
  65524. this._htmlAudioElement.src = "";
  65525. document.body.removeChild(this._htmlAudioElement);
  65526. }
  65527. if (this._streamingSource) {
  65528. this._streamingSource.disconnect();
  65529. }
  65530. if (this._connectedMesh && this._registerFunc) {
  65531. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65532. this._connectedMesh = null;
  65533. }
  65534. }
  65535. };
  65536. Sound.prototype.isReady = function () {
  65537. return this._isReadyToPlay;
  65538. };
  65539. Sound.prototype._soundLoaded = function (audioData) {
  65540. var _this = this;
  65541. if (!BABYLON.Engine.audioEngine.audioContext) {
  65542. return;
  65543. }
  65544. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65545. _this._audioBuffer = buffer;
  65546. _this._isReadyToPlay = true;
  65547. if (_this.autoplay) {
  65548. _this.play();
  65549. }
  65550. if (_this._readyToPlayCallback) {
  65551. _this._readyToPlayCallback();
  65552. }
  65553. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65554. };
  65555. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65556. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65557. this._audioBuffer = audioBuffer;
  65558. this._isReadyToPlay = true;
  65559. }
  65560. };
  65561. Sound.prototype.updateOptions = function (options) {
  65562. if (options) {
  65563. this.loop = options.loop || this.loop;
  65564. this.maxDistance = options.maxDistance || this.maxDistance;
  65565. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65566. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65567. this.refDistance = options.refDistance || this.refDistance;
  65568. this.distanceModel = options.distanceModel || this.distanceModel;
  65569. this._playbackRate = options.playbackRate || this._playbackRate;
  65570. this._updateSpatialParameters();
  65571. if (this.isPlaying) {
  65572. if (this._streaming && this._htmlAudioElement) {
  65573. this._htmlAudioElement.playbackRate = this._playbackRate;
  65574. }
  65575. else {
  65576. if (this._soundSource) {
  65577. this._soundSource.playbackRate.value = this._playbackRate;
  65578. }
  65579. }
  65580. }
  65581. }
  65582. };
  65583. Sound.prototype._createSpatialParameters = function () {
  65584. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65585. if (this._scene.headphone) {
  65586. this._panningModel = "HRTF";
  65587. }
  65588. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65589. this._updateSpatialParameters();
  65590. this._soundPanner.connect(this._outputAudioNode);
  65591. this._inputAudioNode = this._soundPanner;
  65592. }
  65593. };
  65594. Sound.prototype._updateSpatialParameters = function () {
  65595. if (this.spatialSound && this._soundPanner) {
  65596. if (this.useCustomAttenuation) {
  65597. // Tricks to disable in a way embedded Web Audio attenuation
  65598. this._soundPanner.distanceModel = "linear";
  65599. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65600. this._soundPanner.refDistance = 1;
  65601. this._soundPanner.rolloffFactor = 1;
  65602. this._soundPanner.panningModel = this._panningModel;
  65603. }
  65604. else {
  65605. this._soundPanner.distanceModel = this.distanceModel;
  65606. this._soundPanner.maxDistance = this.maxDistance;
  65607. this._soundPanner.refDistance = this.refDistance;
  65608. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65609. this._soundPanner.panningModel = this._panningModel;
  65610. }
  65611. }
  65612. };
  65613. Sound.prototype.switchPanningModelToHRTF = function () {
  65614. this._panningModel = "HRTF";
  65615. this._switchPanningModel();
  65616. };
  65617. Sound.prototype.switchPanningModelToEqualPower = function () {
  65618. this._panningModel = "equalpower";
  65619. this._switchPanningModel();
  65620. };
  65621. Sound.prototype._switchPanningModel = function () {
  65622. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65623. this._soundPanner.panningModel = this._panningModel;
  65624. }
  65625. };
  65626. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65627. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65628. if (this._isOutputConnected) {
  65629. this._outputAudioNode.disconnect();
  65630. }
  65631. this._outputAudioNode.connect(soundTrackAudioNode);
  65632. this._isOutputConnected = true;
  65633. }
  65634. };
  65635. /**
  65636. * Transform this sound into a directional source
  65637. * @param coneInnerAngle Size of the inner cone in degree
  65638. * @param coneOuterAngle Size of the outer cone in degree
  65639. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65640. */
  65641. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65642. if (coneOuterAngle < coneInnerAngle) {
  65643. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65644. return;
  65645. }
  65646. this._coneInnerAngle = coneInnerAngle;
  65647. this._coneOuterAngle = coneOuterAngle;
  65648. this._coneOuterGain = coneOuterGain;
  65649. this._isDirectional = true;
  65650. if (this.isPlaying && this.loop) {
  65651. this.stop();
  65652. this.play();
  65653. }
  65654. };
  65655. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65656. /**
  65657. * Gets or sets the inner angle for the directional cone.
  65658. */
  65659. get: function () {
  65660. return this._coneInnerAngle;
  65661. },
  65662. /**
  65663. * Gets or sets the inner angle for the directional cone.
  65664. */
  65665. set: function (value) {
  65666. if (value != this._coneInnerAngle) {
  65667. if (this._coneOuterAngle < value) {
  65668. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65669. return;
  65670. }
  65671. this._coneInnerAngle = value;
  65672. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65673. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65674. }
  65675. }
  65676. },
  65677. enumerable: true,
  65678. configurable: true
  65679. });
  65680. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65681. /**
  65682. * Gets or sets the outer angle for the directional cone.
  65683. */
  65684. get: function () {
  65685. return this._coneOuterAngle;
  65686. },
  65687. /**
  65688. * Gets or sets the outer angle for the directional cone.
  65689. */
  65690. set: function (value) {
  65691. if (value != this._coneOuterAngle) {
  65692. if (value < this._coneInnerAngle) {
  65693. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65694. return;
  65695. }
  65696. this._coneOuterAngle = value;
  65697. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65698. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65699. }
  65700. }
  65701. },
  65702. enumerable: true,
  65703. configurable: true
  65704. });
  65705. Sound.prototype.setPosition = function (newPosition) {
  65706. this._position = newPosition;
  65707. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65708. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65709. }
  65710. };
  65711. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65712. this._localDirection = newLocalDirection;
  65713. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65714. this._updateDirection();
  65715. }
  65716. };
  65717. Sound.prototype._updateDirection = function () {
  65718. if (!this._connectedMesh || !this._soundPanner) {
  65719. return;
  65720. }
  65721. var mat = this._connectedMesh.getWorldMatrix();
  65722. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65723. direction.normalize();
  65724. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65725. };
  65726. Sound.prototype.updateDistanceFromListener = function () {
  65727. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65728. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65729. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65730. }
  65731. };
  65732. Sound.prototype.setAttenuationFunction = function (callback) {
  65733. this._customAttenuationFunction = callback;
  65734. };
  65735. /**
  65736. * Play the sound
  65737. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65738. * @param offset (optional) Start the sound setting it at a specific time
  65739. */
  65740. Sound.prototype.play = function (time, offset) {
  65741. var _this = this;
  65742. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65743. try {
  65744. if (this._startOffset < 0) {
  65745. time = -this._startOffset;
  65746. this._startOffset = 0;
  65747. }
  65748. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65749. if (!this._soundSource || !this._streamingSource) {
  65750. if (this.spatialSound && this._soundPanner) {
  65751. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65752. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65753. }
  65754. if (this._isDirectional) {
  65755. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65756. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65757. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65758. if (this._connectedMesh) {
  65759. this._updateDirection();
  65760. }
  65761. else {
  65762. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65763. }
  65764. }
  65765. }
  65766. }
  65767. if (this._streaming) {
  65768. if (!this._streamingSource) {
  65769. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65770. this._htmlAudioElement.onended = function () { _this._onended(); };
  65771. this._htmlAudioElement.playbackRate = this._playbackRate;
  65772. }
  65773. this._streamingSource.disconnect();
  65774. this._streamingSource.connect(this._inputAudioNode);
  65775. if (this._htmlAudioElement) {
  65776. this._htmlAudioElement.play();
  65777. }
  65778. }
  65779. else {
  65780. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65781. this._soundSource.buffer = this._audioBuffer;
  65782. this._soundSource.connect(this._inputAudioNode);
  65783. this._soundSource.loop = this.loop;
  65784. this._soundSource.playbackRate.value = this._playbackRate;
  65785. this._soundSource.onended = function () { _this._onended(); };
  65786. if (this._soundSource.buffer) {
  65787. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65788. }
  65789. }
  65790. this._startTime = startTime;
  65791. this.isPlaying = true;
  65792. this.isPaused = false;
  65793. }
  65794. catch (ex) {
  65795. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65796. }
  65797. }
  65798. };
  65799. Sound.prototype._onended = function () {
  65800. this.isPlaying = false;
  65801. if (this.onended) {
  65802. this.onended();
  65803. }
  65804. this.onEndedObservable.notifyObservers(this);
  65805. };
  65806. /**
  65807. * Stop the sound
  65808. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65809. */
  65810. Sound.prototype.stop = function (time) {
  65811. if (this.isPlaying) {
  65812. if (this._streaming) {
  65813. if (this._htmlAudioElement) {
  65814. this._htmlAudioElement.pause();
  65815. // Test needed for Firefox or it will generate an Invalid State Error
  65816. if (this._htmlAudioElement.currentTime > 0) {
  65817. this._htmlAudioElement.currentTime = 0;
  65818. }
  65819. }
  65820. else {
  65821. this._streamingSource.disconnect();
  65822. }
  65823. }
  65824. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65825. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65826. this._soundSource.stop(stopTime);
  65827. this._soundSource.onended = function () { };
  65828. if (!this.isPaused) {
  65829. this._startOffset = 0;
  65830. }
  65831. }
  65832. this.isPlaying = false;
  65833. }
  65834. };
  65835. Sound.prototype.pause = function () {
  65836. if (this.isPlaying) {
  65837. this.isPaused = true;
  65838. if (this._streaming) {
  65839. if (this._htmlAudioElement) {
  65840. this._htmlAudioElement.pause();
  65841. }
  65842. else {
  65843. this._streamingSource.disconnect();
  65844. }
  65845. }
  65846. else if (BABYLON.Engine.audioEngine.audioContext) {
  65847. this.stop(0);
  65848. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65849. }
  65850. }
  65851. };
  65852. Sound.prototype.setVolume = function (newVolume, time) {
  65853. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65854. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65855. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65856. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65857. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65858. }
  65859. else {
  65860. this._soundGain.gain.value = newVolume;
  65861. }
  65862. }
  65863. this._volume = newVolume;
  65864. };
  65865. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65866. this._playbackRate = newPlaybackRate;
  65867. if (this.isPlaying) {
  65868. if (this._streaming && this._htmlAudioElement) {
  65869. this._htmlAudioElement.playbackRate = this._playbackRate;
  65870. }
  65871. else if (this._soundSource) {
  65872. this._soundSource.playbackRate.value = this._playbackRate;
  65873. }
  65874. }
  65875. };
  65876. Sound.prototype.getVolume = function () {
  65877. return this._volume;
  65878. };
  65879. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65880. var _this = this;
  65881. if (this._connectedMesh && this._registerFunc) {
  65882. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65883. this._registerFunc = null;
  65884. }
  65885. this._connectedMesh = meshToConnectTo;
  65886. if (!this.spatialSound) {
  65887. this.spatialSound = true;
  65888. this._createSpatialParameters();
  65889. if (this.isPlaying && this.loop) {
  65890. this.stop();
  65891. this.play();
  65892. }
  65893. }
  65894. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65895. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65896. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65897. };
  65898. Sound.prototype.detachFromMesh = function () {
  65899. if (this._connectedMesh && this._registerFunc) {
  65900. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65901. this._registerFunc = null;
  65902. this._connectedMesh = null;
  65903. }
  65904. };
  65905. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65906. if (!node.getBoundingInfo) {
  65907. return;
  65908. }
  65909. var mesh = node;
  65910. if (this._positionInEmitterSpace) {
  65911. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65912. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65913. }
  65914. else {
  65915. var boundingInfo = mesh.getBoundingInfo();
  65916. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65917. }
  65918. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65919. this._updateDirection();
  65920. }
  65921. };
  65922. Sound.prototype.clone = function () {
  65923. var _this = this;
  65924. if (!this._streaming) {
  65925. var setBufferAndRun = function () {
  65926. if (_this._isReadyToPlay) {
  65927. clonedSound._audioBuffer = _this.getAudioBuffer();
  65928. clonedSound._isReadyToPlay = true;
  65929. if (clonedSound.autoplay) {
  65930. clonedSound.play();
  65931. }
  65932. }
  65933. else {
  65934. window.setTimeout(setBufferAndRun, 300);
  65935. }
  65936. };
  65937. var currentOptions = {
  65938. autoplay: this.autoplay, loop: this.loop,
  65939. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65940. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65941. refDistance: this.refDistance, distanceModel: this.distanceModel
  65942. };
  65943. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65944. if (this.useCustomAttenuation) {
  65945. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65946. }
  65947. clonedSound.setPosition(this._position);
  65948. clonedSound.setPlaybackRate(this._playbackRate);
  65949. setBufferAndRun();
  65950. return clonedSound;
  65951. }
  65952. // Can't clone a streaming sound
  65953. else {
  65954. return null;
  65955. }
  65956. };
  65957. Sound.prototype.getAudioBuffer = function () {
  65958. return this._audioBuffer;
  65959. };
  65960. Sound.prototype.serialize = function () {
  65961. var serializationObject = {
  65962. name: this.name,
  65963. url: this.name,
  65964. autoplay: this.autoplay,
  65965. loop: this.loop,
  65966. volume: this._volume,
  65967. spatialSound: this.spatialSound,
  65968. maxDistance: this.maxDistance,
  65969. rolloffFactor: this.rolloffFactor,
  65970. refDistance: this.refDistance,
  65971. distanceModel: this.distanceModel,
  65972. playbackRate: this._playbackRate,
  65973. panningModel: this._panningModel,
  65974. soundTrackId: this.soundTrackId
  65975. };
  65976. if (this.spatialSound) {
  65977. if (this._connectedMesh)
  65978. serializationObject.connectedMeshId = this._connectedMesh.id;
  65979. serializationObject.position = this._position.asArray();
  65980. serializationObject.refDistance = this.refDistance;
  65981. serializationObject.distanceModel = this.distanceModel;
  65982. serializationObject.isDirectional = this._isDirectional;
  65983. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65984. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65985. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65986. serializationObject.coneOuterGain = this._coneOuterGain;
  65987. }
  65988. return serializationObject;
  65989. };
  65990. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65991. var soundName = parsedSound.name;
  65992. var soundUrl;
  65993. if (parsedSound.url) {
  65994. soundUrl = rootUrl + parsedSound.url;
  65995. }
  65996. else {
  65997. soundUrl = rootUrl + soundName;
  65998. }
  65999. var options = {
  66000. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66001. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66002. rolloffFactor: parsedSound.rolloffFactor,
  66003. refDistance: parsedSound.refDistance,
  66004. distanceModel: parsedSound.distanceModel,
  66005. playbackRate: parsedSound.playbackRate
  66006. };
  66007. var newSound;
  66008. if (!sourceSound) {
  66009. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66010. scene._addPendingData(newSound);
  66011. }
  66012. else {
  66013. var setBufferAndRun = function () {
  66014. if (sourceSound._isReadyToPlay) {
  66015. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66016. newSound._isReadyToPlay = true;
  66017. if (newSound.autoplay) {
  66018. newSound.play();
  66019. }
  66020. }
  66021. else {
  66022. window.setTimeout(setBufferAndRun, 300);
  66023. }
  66024. };
  66025. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66026. setBufferAndRun();
  66027. }
  66028. if (parsedSound.position) {
  66029. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66030. newSound.setPosition(soundPosition);
  66031. }
  66032. if (parsedSound.isDirectional) {
  66033. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66034. if (parsedSound.localDirectionToMesh) {
  66035. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66036. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66037. }
  66038. }
  66039. if (parsedSound.connectedMeshId) {
  66040. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66041. if (connectedMesh) {
  66042. newSound.attachToMesh(connectedMesh);
  66043. }
  66044. }
  66045. return newSound;
  66046. };
  66047. return Sound;
  66048. }());
  66049. BABYLON.Sound = Sound;
  66050. })(BABYLON || (BABYLON = {}));
  66051. //# sourceMappingURL=babylon.sound.js.map
  66052. var BABYLON;
  66053. (function (BABYLON) {
  66054. var SoundTrack = /** @class */ (function () {
  66055. function SoundTrack(scene, options) {
  66056. this.id = -1;
  66057. this._isMainTrack = false;
  66058. this._isInitialized = false;
  66059. this._scene = scene;
  66060. this.soundCollection = new Array();
  66061. this._options = options;
  66062. if (!this._isMainTrack) {
  66063. this._scene.soundTracks.push(this);
  66064. this.id = this._scene.soundTracks.length - 1;
  66065. }
  66066. }
  66067. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66068. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66069. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66070. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66071. if (this._options) {
  66072. if (this._options.volume) {
  66073. this._outputAudioNode.gain.value = this._options.volume;
  66074. }
  66075. if (this._options.mainTrack) {
  66076. this._isMainTrack = this._options.mainTrack;
  66077. }
  66078. }
  66079. this._isInitialized = true;
  66080. }
  66081. };
  66082. SoundTrack.prototype.dispose = function () {
  66083. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66084. if (this._connectedAnalyser) {
  66085. this._connectedAnalyser.stopDebugCanvas();
  66086. }
  66087. while (this.soundCollection.length) {
  66088. this.soundCollection[0].dispose();
  66089. }
  66090. if (this._outputAudioNode) {
  66091. this._outputAudioNode.disconnect();
  66092. }
  66093. this._outputAudioNode = null;
  66094. }
  66095. };
  66096. SoundTrack.prototype.AddSound = function (sound) {
  66097. if (!this._isInitialized) {
  66098. this._initializeSoundTrackAudioGraph();
  66099. }
  66100. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66101. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66102. }
  66103. if (sound.soundTrackId) {
  66104. if (sound.soundTrackId === -1) {
  66105. this._scene.mainSoundTrack.RemoveSound(sound);
  66106. }
  66107. else {
  66108. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66109. }
  66110. }
  66111. this.soundCollection.push(sound);
  66112. sound.soundTrackId = this.id;
  66113. };
  66114. SoundTrack.prototype.RemoveSound = function (sound) {
  66115. var index = this.soundCollection.indexOf(sound);
  66116. if (index !== -1) {
  66117. this.soundCollection.splice(index, 1);
  66118. }
  66119. };
  66120. SoundTrack.prototype.setVolume = function (newVolume) {
  66121. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66122. this._outputAudioNode.gain.value = newVolume;
  66123. }
  66124. };
  66125. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66126. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66127. for (var i = 0; i < this.soundCollection.length; i++) {
  66128. this.soundCollection[i].switchPanningModelToHRTF();
  66129. }
  66130. }
  66131. };
  66132. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66134. for (var i = 0; i < this.soundCollection.length; i++) {
  66135. this.soundCollection[i].switchPanningModelToEqualPower();
  66136. }
  66137. }
  66138. };
  66139. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66140. if (this._connectedAnalyser) {
  66141. this._connectedAnalyser.stopDebugCanvas();
  66142. }
  66143. this._connectedAnalyser = analyser;
  66144. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66145. this._outputAudioNode.disconnect();
  66146. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66147. }
  66148. };
  66149. return SoundTrack;
  66150. }());
  66151. BABYLON.SoundTrack = SoundTrack;
  66152. })(BABYLON || (BABYLON = {}));
  66153. //# sourceMappingURL=babylon.soundtrack.js.map
  66154. var BABYLON;
  66155. (function (BABYLON) {
  66156. /**
  66157. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66158. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66159. */
  66160. var Analyser = /** @class */ (function () {
  66161. /**
  66162. * Creates a new analyser
  66163. * @param scene defines hosting scene
  66164. */
  66165. function Analyser(scene) {
  66166. /**
  66167. * Gets or sets the smoothing
  66168. * @ignorenaming
  66169. */
  66170. this.SMOOTHING = 0.75;
  66171. /**
  66172. * Gets or sets the FFT table size
  66173. * @ignorenaming
  66174. */
  66175. this.FFT_SIZE = 512;
  66176. /**
  66177. * Gets or sets the bar graph amplitude
  66178. * @ignorenaming
  66179. */
  66180. this.BARGRAPHAMPLITUDE = 256;
  66181. /**
  66182. * Gets or sets the position of the debug canvas
  66183. * @ignorenaming
  66184. */
  66185. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66186. /**
  66187. * Gets or sets the debug canvas size
  66188. * @ignorenaming
  66189. */
  66190. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66191. this._scene = scene;
  66192. this._audioEngine = BABYLON.Engine.audioEngine;
  66193. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66194. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66195. this._webAudioAnalyser.minDecibels = -140;
  66196. this._webAudioAnalyser.maxDecibels = 0;
  66197. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66198. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66199. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66200. }
  66201. }
  66202. /**
  66203. * Get the number of data values you will have to play with for the visualization
  66204. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66205. * @returns a number
  66206. */
  66207. Analyser.prototype.getFrequencyBinCount = function () {
  66208. if (this._audioEngine.canUseWebAudio) {
  66209. return this._webAudioAnalyser.frequencyBinCount;
  66210. }
  66211. else {
  66212. return 0;
  66213. }
  66214. };
  66215. /**
  66216. * Gets the current frequency data as a byte array
  66217. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66218. * @returns a Uint8Array
  66219. */
  66220. Analyser.prototype.getByteFrequencyData = function () {
  66221. if (this._audioEngine.canUseWebAudio) {
  66222. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66223. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66224. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66225. }
  66226. return this._byteFreqs;
  66227. };
  66228. /**
  66229. * Gets the current waveform as a byte array
  66230. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66231. * @returns a Uint8Array
  66232. */
  66233. Analyser.prototype.getByteTimeDomainData = function () {
  66234. if (this._audioEngine.canUseWebAudio) {
  66235. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66236. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66237. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66238. }
  66239. return this._byteTime;
  66240. };
  66241. /**
  66242. * Gets the current frequency data as a float array
  66243. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66244. * @returns a Float32Array
  66245. */
  66246. Analyser.prototype.getFloatFrequencyData = function () {
  66247. if (this._audioEngine.canUseWebAudio) {
  66248. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66249. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66250. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66251. }
  66252. return this._floatFreqs;
  66253. };
  66254. /**
  66255. * Renders the debug canvas
  66256. */
  66257. Analyser.prototype.drawDebugCanvas = function () {
  66258. var _this = this;
  66259. if (this._audioEngine.canUseWebAudio) {
  66260. if (!this._debugCanvas) {
  66261. this._debugCanvas = document.createElement("canvas");
  66262. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66263. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66264. this._debugCanvas.style.position = "absolute";
  66265. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66266. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66267. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66268. document.body.appendChild(this._debugCanvas);
  66269. this._registerFunc = function () {
  66270. _this.drawDebugCanvas();
  66271. };
  66272. this._scene.registerBeforeRender(this._registerFunc);
  66273. }
  66274. if (this._registerFunc && this._debugCanvasContext) {
  66275. var workingArray = this.getByteFrequencyData();
  66276. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66277. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66278. // Draw the frequency domain chart.
  66279. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66280. var value = workingArray[i];
  66281. var percent = value / this.BARGRAPHAMPLITUDE;
  66282. var height = this.DEBUGCANVASSIZE.height * percent;
  66283. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66284. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66285. var hue = i / this.getFrequencyBinCount() * 360;
  66286. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66287. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66288. }
  66289. }
  66290. }
  66291. };
  66292. /**
  66293. * Stops rendering the debug canvas and removes it
  66294. */
  66295. Analyser.prototype.stopDebugCanvas = function () {
  66296. if (this._debugCanvas) {
  66297. if (this._registerFunc) {
  66298. this._scene.unregisterBeforeRender(this._registerFunc);
  66299. this._registerFunc = null;
  66300. }
  66301. document.body.removeChild(this._debugCanvas);
  66302. this._debugCanvas = null;
  66303. this._debugCanvasContext = null;
  66304. }
  66305. };
  66306. /**
  66307. * Connects two audio nodes
  66308. * @param inputAudioNode defines first node to connect
  66309. * @param outputAudioNode defines second node to connect
  66310. */
  66311. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66312. if (this._audioEngine.canUseWebAudio) {
  66313. inputAudioNode.connect(this._webAudioAnalyser);
  66314. this._webAudioAnalyser.connect(outputAudioNode);
  66315. }
  66316. };
  66317. /**
  66318. * Releases all associated resources
  66319. */
  66320. Analyser.prototype.dispose = function () {
  66321. if (this._audioEngine.canUseWebAudio) {
  66322. this._webAudioAnalyser.disconnect();
  66323. }
  66324. };
  66325. return Analyser;
  66326. }());
  66327. BABYLON.Analyser = Analyser;
  66328. })(BABYLON || (BABYLON = {}));
  66329. //# sourceMappingURL=babylon.analyser.js.map
  66330. var BABYLON;
  66331. (function (BABYLON) {
  66332. /**
  66333. * Wraps one or more Sound objects and selects one with random weight for playback.
  66334. */
  66335. var WeightedSound = /** @class */ (function () {
  66336. /**
  66337. * Creates a new WeightedSound from the list of sounds given.
  66338. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66339. * @param sounds Array of Sounds that will be selected from.
  66340. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66341. */
  66342. function WeightedSound(loop, sounds, weights) {
  66343. var _this = this;
  66344. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66345. this.loop = false;
  66346. this._coneInnerAngle = 360;
  66347. this._coneOuterAngle = 360;
  66348. this._volume = 1;
  66349. /** A Sound is currently playing. */
  66350. this.isPlaying = false;
  66351. /** A Sound is currently paused. */
  66352. this.isPaused = false;
  66353. this._sounds = [];
  66354. this._weights = [];
  66355. if (sounds.length !== weights.length) {
  66356. throw new Error('Sounds length does not equal weights length');
  66357. }
  66358. this.loop = loop;
  66359. this._weights = weights;
  66360. // Normalize the weights
  66361. var weightSum = 0;
  66362. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66363. var weight = weights_1[_i];
  66364. weightSum += weight;
  66365. }
  66366. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66367. for (var i = 0; i < this._weights.length; i++) {
  66368. this._weights[i] *= invWeightSum;
  66369. }
  66370. this._sounds = sounds;
  66371. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66372. var sound = _b[_a];
  66373. sound.onEndedObservable.add(function () { _this._onended(); });
  66374. }
  66375. }
  66376. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66377. /**
  66378. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66379. */
  66380. get: function () {
  66381. return this._coneInnerAngle;
  66382. },
  66383. /**
  66384. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66385. */
  66386. set: function (value) {
  66387. if (value !== this._coneInnerAngle) {
  66388. if (this._coneOuterAngle < value) {
  66389. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66390. return;
  66391. }
  66392. this._coneInnerAngle = value;
  66393. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66394. var sound = _a[_i];
  66395. sound.directionalConeInnerAngle = value;
  66396. }
  66397. }
  66398. },
  66399. enumerable: true,
  66400. configurable: true
  66401. });
  66402. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66403. /**
  66404. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66405. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66406. */
  66407. get: function () {
  66408. return this._coneOuterAngle;
  66409. },
  66410. /**
  66411. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66412. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66413. */
  66414. set: function (value) {
  66415. if (value !== this._coneOuterAngle) {
  66416. if (value < this._coneInnerAngle) {
  66417. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66418. return;
  66419. }
  66420. this._coneOuterAngle = value;
  66421. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66422. var sound = _a[_i];
  66423. sound.directionalConeOuterAngle = value;
  66424. }
  66425. }
  66426. },
  66427. enumerable: true,
  66428. configurable: true
  66429. });
  66430. Object.defineProperty(WeightedSound.prototype, "volume", {
  66431. /**
  66432. * Playback volume.
  66433. */
  66434. get: function () {
  66435. return this._volume;
  66436. },
  66437. /**
  66438. * Playback volume.
  66439. */
  66440. set: function (value) {
  66441. if (value !== this._volume) {
  66442. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66443. var sound = _a[_i];
  66444. sound.setVolume(value);
  66445. }
  66446. }
  66447. },
  66448. enumerable: true,
  66449. configurable: true
  66450. });
  66451. WeightedSound.prototype._onended = function () {
  66452. if (this._currentIndex !== undefined) {
  66453. this._sounds[this._currentIndex].autoplay = false;
  66454. }
  66455. if (this.loop && this.isPlaying) {
  66456. this.play();
  66457. }
  66458. else {
  66459. this.isPlaying = false;
  66460. }
  66461. };
  66462. /**
  66463. * Suspend playback
  66464. */
  66465. WeightedSound.prototype.pause = function () {
  66466. this.isPaused = true;
  66467. if (this._currentIndex !== undefined) {
  66468. this._sounds[this._currentIndex].pause();
  66469. }
  66470. };
  66471. /**
  66472. * Stop playback
  66473. */
  66474. WeightedSound.prototype.stop = function () {
  66475. this.isPlaying = false;
  66476. if (this._currentIndex !== undefined) {
  66477. this._sounds[this._currentIndex].stop();
  66478. }
  66479. };
  66480. /**
  66481. * Start playback.
  66482. * @param startOffset Position the clip head at a specific time in seconds.
  66483. */
  66484. WeightedSound.prototype.play = function (startOffset) {
  66485. if (!this.isPaused) {
  66486. this.stop();
  66487. var randomValue = Math.random();
  66488. var total = 0;
  66489. for (var i = 0; i < this._weights.length; i++) {
  66490. total += this._weights[i];
  66491. if (randomValue <= total) {
  66492. this._currentIndex = i;
  66493. break;
  66494. }
  66495. }
  66496. }
  66497. var sound = this._sounds[this._currentIndex];
  66498. if (sound.isReady()) {
  66499. sound.play(0, this.isPaused ? undefined : startOffset);
  66500. }
  66501. else {
  66502. sound.autoplay = true;
  66503. }
  66504. this.isPlaying = true;
  66505. this.isPaused = false;
  66506. };
  66507. return WeightedSound;
  66508. }());
  66509. BABYLON.WeightedSound = WeightedSound;
  66510. })(BABYLON || (BABYLON = {}));
  66511. //# sourceMappingURL=babylon.weightedsound.js.map
  66512. var BABYLON;
  66513. (function (BABYLON) {
  66514. var CubeTexture = /** @class */ (function (_super) {
  66515. __extends(CubeTexture, _super);
  66516. /**
  66517. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66518. * as prefiltered data.
  66519. * @param rootUrl defines the url of the texture or the root name of the six images
  66520. * @param scene defines the scene the texture is attached to
  66521. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66522. * @param noMipmap defines if mipmaps should be created or not
  66523. * @param files defines the six files to load for the different faces
  66524. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66525. * @param onError defines a callback triggered in case of error during load
  66526. * @param format defines the internal format to use for the texture once loaded
  66527. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66528. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66529. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66530. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66531. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66532. * @return the cube texture
  66533. */
  66534. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66535. if (extensions === void 0) { extensions = null; }
  66536. if (noMipmap === void 0) { noMipmap = false; }
  66537. if (files === void 0) { files = null; }
  66538. if (onLoad === void 0) { onLoad = null; }
  66539. if (onError === void 0) { onError = null; }
  66540. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66541. if (prefiltered === void 0) { prefiltered = false; }
  66542. if (forcedExtension === void 0) { forcedExtension = null; }
  66543. if (createPolynomials === void 0) { createPolynomials = false; }
  66544. if (lodScale === void 0) { lodScale = 0.8; }
  66545. if (lodOffset === void 0) { lodOffset = 0; }
  66546. var _this = _super.call(this, scene) || this;
  66547. /**
  66548. * Gets or sets the center of the bounding box associated with the cube texture
  66549. * It must define where the camera used to render the texture was set
  66550. */
  66551. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66552. _this._rotationY = 0;
  66553. /** @hidden */
  66554. _this._prefiltered = false;
  66555. _this.name = rootUrl;
  66556. _this.url = rootUrl;
  66557. _this._noMipmap = noMipmap;
  66558. _this.hasAlpha = false;
  66559. _this._format = format;
  66560. _this.isCube = true;
  66561. _this._textureMatrix = BABYLON.Matrix.Identity();
  66562. _this._createPolynomials = createPolynomials;
  66563. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66564. if (!rootUrl && !files) {
  66565. return _this;
  66566. }
  66567. var lastDot = rootUrl.lastIndexOf(".");
  66568. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66569. var isDDS = (extension === ".dds");
  66570. var isEnv = (extension === ".env");
  66571. if (isEnv) {
  66572. _this.gammaSpace = false;
  66573. _this._prefiltered = false;
  66574. }
  66575. else {
  66576. _this._prefiltered = prefiltered;
  66577. if (prefiltered) {
  66578. _this.gammaSpace = false;
  66579. }
  66580. }
  66581. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66582. if (!files) {
  66583. if (!isEnv && !isDDS && !extensions) {
  66584. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66585. }
  66586. files = [];
  66587. if (extensions) {
  66588. for (var index = 0; index < extensions.length; index++) {
  66589. files.push(rootUrl + extensions[index]);
  66590. }
  66591. }
  66592. }
  66593. _this._files = files;
  66594. if (!_this._texture) {
  66595. if (!scene.useDelayedTextureLoading) {
  66596. if (prefiltered) {
  66597. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66598. }
  66599. else {
  66600. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66601. }
  66602. }
  66603. else {
  66604. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66605. }
  66606. }
  66607. else if (onLoad) {
  66608. if (_this._texture.isReady) {
  66609. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66610. }
  66611. else {
  66612. _this._texture.onLoadedObservable.add(onLoad);
  66613. }
  66614. }
  66615. return _this;
  66616. }
  66617. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66618. get: function () {
  66619. return this._boundingBoxSize;
  66620. },
  66621. /**
  66622. * Gets or sets the size of the bounding box associated with the cube texture
  66623. * When defined, the cubemap will switch to local mode
  66624. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66625. * @example https://www.babylonjs-playground.com/#RNASML
  66626. */
  66627. set: function (value) {
  66628. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66629. return;
  66630. }
  66631. this._boundingBoxSize = value;
  66632. var scene = this.getScene();
  66633. if (scene) {
  66634. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66635. }
  66636. },
  66637. enumerable: true,
  66638. configurable: true
  66639. });
  66640. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66641. /**
  66642. * Gets texture matrix rotation angle around Y axis radians.
  66643. */
  66644. get: function () {
  66645. return this._rotationY;
  66646. },
  66647. /**
  66648. * Sets texture matrix rotation angle around Y axis in radians.
  66649. */
  66650. set: function (value) {
  66651. this._rotationY = value;
  66652. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66653. },
  66654. enumerable: true,
  66655. configurable: true
  66656. });
  66657. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66658. var rootUrlKey = "";
  66659. files.forEach(function (url) { return rootUrlKey += url; });
  66660. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66661. };
  66662. /**
  66663. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66664. * @param url defines the url of the prefiltered texture
  66665. * @param scene defines the scene the texture is attached to
  66666. * @param forcedExtension defines the extension of the file if different from the url
  66667. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66668. * @return the prefiltered texture
  66669. */
  66670. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66671. if (forcedExtension === void 0) { forcedExtension = null; }
  66672. if (createPolynomials === void 0) { createPolynomials = true; }
  66673. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66674. };
  66675. // Methods
  66676. CubeTexture.prototype.delayLoad = function () {
  66677. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66678. return;
  66679. }
  66680. var scene = this.getScene();
  66681. if (!scene) {
  66682. return;
  66683. }
  66684. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66685. this._texture = this._getFromCache(this.url, this._noMipmap);
  66686. if (!this._texture) {
  66687. if (this._prefiltered) {
  66688. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66689. }
  66690. else {
  66691. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66692. }
  66693. }
  66694. };
  66695. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66696. return this._textureMatrix;
  66697. };
  66698. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66699. this._textureMatrix = value;
  66700. };
  66701. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66702. var texture = BABYLON.SerializationHelper.Parse(function () {
  66703. var prefiltered = false;
  66704. if (parsedTexture.prefiltered) {
  66705. prefiltered = parsedTexture.prefiltered;
  66706. }
  66707. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66708. }, parsedTexture, scene);
  66709. // Local Cubemaps
  66710. if (parsedTexture.boundingBoxPosition) {
  66711. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66712. }
  66713. if (parsedTexture.boundingBoxSize) {
  66714. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66715. }
  66716. // Animations
  66717. if (parsedTexture.animations) {
  66718. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66719. var parsedAnimation = parsedTexture.animations[animationIndex];
  66720. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66721. }
  66722. }
  66723. return texture;
  66724. };
  66725. CubeTexture.prototype.clone = function () {
  66726. var _this = this;
  66727. return BABYLON.SerializationHelper.Clone(function () {
  66728. var scene = _this.getScene();
  66729. if (!scene) {
  66730. return _this;
  66731. }
  66732. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66733. }, this);
  66734. };
  66735. __decorate([
  66736. BABYLON.serialize("rotationY")
  66737. ], CubeTexture.prototype, "rotationY", null);
  66738. return CubeTexture;
  66739. }(BABYLON.BaseTexture));
  66740. BABYLON.CubeTexture = CubeTexture;
  66741. })(BABYLON || (BABYLON = {}));
  66742. //# sourceMappingURL=babylon.cubeTexture.js.map
  66743. var BABYLON;
  66744. (function (BABYLON) {
  66745. /**
  66746. * Raw cube texture where the raw buffers are passed in
  66747. */
  66748. var RawCubeTexture = /** @class */ (function (_super) {
  66749. __extends(RawCubeTexture, _super);
  66750. /**
  66751. * Creates a cube texture where the raw buffers are passed in.
  66752. * @param scene defines the scene the texture is attached to
  66753. * @param data defines the array of data to use to create each face
  66754. * @param size defines the size of the textures
  66755. * @param format defines the format of the data
  66756. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66757. * @param generateMipMaps defines if the engine should generate the mip levels
  66758. * @param invertY defines if data must be stored with Y axis inverted
  66759. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66760. * @param compression defines the compression used (null by default)
  66761. */
  66762. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66763. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66764. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66765. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66766. if (invertY === void 0) { invertY = false; }
  66767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66768. if (compression === void 0) { compression = null; }
  66769. var _this = _super.call(this, "", scene) || this;
  66770. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66771. return _this;
  66772. }
  66773. /**
  66774. * Updates the raw cube texture.
  66775. * @param data defines the data to store
  66776. * @param format defines the data format
  66777. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66778. * @param invertY defines if data must be stored with Y axis inverted
  66779. * @param compression defines the compression used (null by default)
  66780. * @param level defines which level of the texture to update
  66781. */
  66782. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66783. if (compression === void 0) { compression = null; }
  66784. if (level === void 0) { level = 0; }
  66785. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66786. };
  66787. /**
  66788. * Updates a raw cube texture with RGBD encoded data.
  66789. * @param data defines the array of data [mipmap][face] to use to create each face
  66790. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66791. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66792. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66793. * @returns a promsie that resolves when the operation is complete
  66794. */
  66795. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66796. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66797. if (lodScale === void 0) { lodScale = 0.8; }
  66798. if (lodOffset === void 0) { lodOffset = 0; }
  66799. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66800. };
  66801. /**
  66802. * Clones the raw cube texture.
  66803. * @return a new cube texture
  66804. */
  66805. RawCubeTexture.prototype.clone = function () {
  66806. var _this = this;
  66807. return BABYLON.SerializationHelper.Clone(function () {
  66808. var scene = _this.getScene();
  66809. var internalTexture = _this._texture;
  66810. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66811. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66812. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66813. }
  66814. return texture;
  66815. }, this);
  66816. };
  66817. /** @hidden */
  66818. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66819. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66820. internalTexture._bufferViewArrayArray = data;
  66821. internalTexture._lodGenerationScale = lodScale;
  66822. internalTexture._lodGenerationOffset = lodOffset;
  66823. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66824. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66825. internalTexture.isReady = true;
  66826. });
  66827. };
  66828. return RawCubeTexture;
  66829. }(BABYLON.CubeTexture));
  66830. BABYLON.RawCubeTexture = RawCubeTexture;
  66831. })(BABYLON || (BABYLON = {}));
  66832. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66833. var BABYLON;
  66834. (function (BABYLON) {
  66835. var RenderTargetTexture = /** @class */ (function (_super) {
  66836. __extends(RenderTargetTexture, _super);
  66837. /**
  66838. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66839. * or used a shadow, depth texture...
  66840. * @param name The friendly name of the texture
  66841. * @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)
  66842. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66843. * @param generateMipMaps True if mip maps need to be generated after render.
  66844. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66845. * @param type The type of the buffer in the RTT (int, half float, float...)
  66846. * @param isCube True if a cube texture needs to be created
  66847. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66848. * @param generateDepthBuffer True to generate a depth buffer
  66849. * @param generateStencilBuffer True to generate a stencil buffer
  66850. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66851. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66852. */
  66853. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66854. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66855. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66856. if (isCube === void 0) { isCube = false; }
  66857. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66858. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66859. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66860. if (isMulti === void 0) { isMulti = false; }
  66861. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66862. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66863. _this.isCube = isCube;
  66864. _this.renderParticles = true;
  66865. _this.renderSprites = false;
  66866. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66867. _this.ignoreCameraViewport = false;
  66868. // Events
  66869. /**
  66870. * An event triggered when the texture is unbind.
  66871. */
  66872. _this.onBeforeBindObservable = new BABYLON.Observable();
  66873. /**
  66874. * An event triggered when the texture is unbind.
  66875. */
  66876. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66877. /**
  66878. * An event triggered before rendering the texture
  66879. */
  66880. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66881. /**
  66882. * An event triggered after rendering the texture
  66883. */
  66884. _this.onAfterRenderObservable = new BABYLON.Observable();
  66885. /**
  66886. * An event triggered after the texture clear
  66887. */
  66888. _this.onClearObservable = new BABYLON.Observable();
  66889. _this._currentRefreshId = -1;
  66890. _this._refreshRate = 1;
  66891. _this._samples = 1;
  66892. /**
  66893. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66894. * It must define where the camera used to render the texture is set
  66895. */
  66896. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66897. scene = _this.getScene();
  66898. if (!scene) {
  66899. return _this;
  66900. }
  66901. _this.renderList = new Array();
  66902. _this._engine = scene.getEngine();
  66903. _this.name = name;
  66904. _this.isRenderTarget = true;
  66905. _this._initialSizeParameter = size;
  66906. _this._processSizeParameter(size);
  66907. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66908. });
  66909. _this._generateMipMaps = generateMipMaps ? true : false;
  66910. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66911. // Rendering groups
  66912. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66913. _this._renderingManager._useSceneAutoClearSetup = true;
  66914. if (isMulti) {
  66915. return _this;
  66916. }
  66917. _this._renderTargetOptions = {
  66918. generateMipMaps: generateMipMaps,
  66919. type: type,
  66920. format: format,
  66921. samplingMode: samplingMode,
  66922. generateDepthBuffer: generateDepthBuffer,
  66923. generateStencilBuffer: generateStencilBuffer
  66924. };
  66925. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66926. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66927. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66928. }
  66929. if (isCube) {
  66930. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66931. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66932. _this._textureMatrix = BABYLON.Matrix.Identity();
  66933. }
  66934. else {
  66935. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66936. }
  66937. return _this;
  66938. }
  66939. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66940. get: function () {
  66941. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66942. },
  66943. enumerable: true,
  66944. configurable: true
  66945. });
  66946. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66947. get: function () {
  66948. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66949. },
  66950. enumerable: true,
  66951. configurable: true
  66952. });
  66953. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66954. get: function () {
  66955. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66956. },
  66957. enumerable: true,
  66958. configurable: true
  66959. });
  66960. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66961. /**
  66962. * Use this list to define the list of mesh you want to render.
  66963. */
  66964. get: function () {
  66965. return this._renderList;
  66966. },
  66967. set: function (value) {
  66968. this._renderList = value;
  66969. if (this._renderList) {
  66970. this._hookArray(this._renderList);
  66971. }
  66972. },
  66973. enumerable: true,
  66974. configurable: true
  66975. });
  66976. RenderTargetTexture.prototype._hookArray = function (array) {
  66977. var _this = this;
  66978. var oldPush = array.push;
  66979. array.push = function () {
  66980. var items = [];
  66981. for (var _i = 0; _i < arguments.length; _i++) {
  66982. items[_i] = arguments[_i];
  66983. }
  66984. var result = oldPush.apply(array, items);
  66985. _this.getScene().meshes.forEach(function (mesh) {
  66986. mesh._markSubMeshesAsLightDirty();
  66987. });
  66988. return result;
  66989. };
  66990. var oldSplice = array.splice;
  66991. array.splice = function (index, deleteCount) {
  66992. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66993. _this.getScene().meshes.forEach(function (mesh) {
  66994. mesh._markSubMeshesAsLightDirty();
  66995. });
  66996. return deleted;
  66997. };
  66998. };
  66999. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67000. set: function (callback) {
  67001. if (this._onAfterUnbindObserver) {
  67002. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67003. }
  67004. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67005. },
  67006. enumerable: true,
  67007. configurable: true
  67008. });
  67009. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67010. set: function (callback) {
  67011. if (this._onBeforeRenderObserver) {
  67012. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67013. }
  67014. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67015. },
  67016. enumerable: true,
  67017. configurable: true
  67018. });
  67019. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67020. set: function (callback) {
  67021. if (this._onAfterRenderObserver) {
  67022. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67023. }
  67024. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67025. },
  67026. enumerable: true,
  67027. configurable: true
  67028. });
  67029. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67030. set: function (callback) {
  67031. if (this._onClearObserver) {
  67032. this.onClearObservable.remove(this._onClearObserver);
  67033. }
  67034. this._onClearObserver = this.onClearObservable.add(callback);
  67035. },
  67036. enumerable: true,
  67037. configurable: true
  67038. });
  67039. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67040. get: function () {
  67041. return this._renderTargetOptions;
  67042. },
  67043. enumerable: true,
  67044. configurable: true
  67045. });
  67046. RenderTargetTexture.prototype._onRatioRescale = function () {
  67047. if (this._sizeRatio) {
  67048. this.resize(this._initialSizeParameter);
  67049. }
  67050. };
  67051. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67052. get: function () {
  67053. return this._boundingBoxSize;
  67054. },
  67055. /**
  67056. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67057. * When defined, the cubemap will switch to local mode
  67058. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67059. * @example https://www.babylonjs-playground.com/#RNASML
  67060. */
  67061. set: function (value) {
  67062. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67063. return;
  67064. }
  67065. this._boundingBoxSize = value;
  67066. var scene = this.getScene();
  67067. if (scene) {
  67068. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67069. }
  67070. },
  67071. enumerable: true,
  67072. configurable: true
  67073. });
  67074. /**
  67075. * Creates a depth stencil texture.
  67076. * This is only available in WebGL 2 or with the depth texture extension available.
  67077. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67078. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67079. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67080. */
  67081. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67082. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67083. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67084. if (generateStencil === void 0) { generateStencil = false; }
  67085. if (!this.getScene()) {
  67086. return;
  67087. }
  67088. var engine = this.getScene().getEngine();
  67089. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67090. bilinearFiltering: bilinearFiltering,
  67091. comparisonFunction: comparisonFunction,
  67092. generateStencil: generateStencil,
  67093. isCube: this.isCube
  67094. });
  67095. engine.setFrameBufferDepthStencilTexture(this);
  67096. };
  67097. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67098. if (size.ratio) {
  67099. this._sizeRatio = size.ratio;
  67100. this._size = {
  67101. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67102. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67103. };
  67104. }
  67105. else {
  67106. this._size = size;
  67107. }
  67108. };
  67109. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67110. get: function () {
  67111. return this._samples;
  67112. },
  67113. set: function (value) {
  67114. if (this._samples === value) {
  67115. return;
  67116. }
  67117. var scene = this.getScene();
  67118. if (!scene) {
  67119. return;
  67120. }
  67121. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67122. },
  67123. enumerable: true,
  67124. configurable: true
  67125. });
  67126. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67127. this._currentRefreshId = -1;
  67128. };
  67129. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67130. get: function () {
  67131. return this._refreshRate;
  67132. },
  67133. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67134. set: function (value) {
  67135. this._refreshRate = value;
  67136. this.resetRefreshCounter();
  67137. },
  67138. enumerable: true,
  67139. configurable: true
  67140. });
  67141. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67142. if (!this._postProcessManager) {
  67143. var scene = this.getScene();
  67144. if (!scene) {
  67145. return;
  67146. }
  67147. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67148. this._postProcesses = new Array();
  67149. }
  67150. this._postProcesses.push(postProcess);
  67151. this._postProcesses[0].autoClear = false;
  67152. };
  67153. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67154. if (!this._postProcesses) {
  67155. return;
  67156. }
  67157. if (dispose) {
  67158. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67159. var postProcess = _a[_i];
  67160. postProcess.dispose();
  67161. }
  67162. }
  67163. this._postProcesses = [];
  67164. };
  67165. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67166. if (!this._postProcesses) {
  67167. return;
  67168. }
  67169. var index = this._postProcesses.indexOf(postProcess);
  67170. if (index === -1) {
  67171. return;
  67172. }
  67173. this._postProcesses.splice(index, 1);
  67174. if (this._postProcesses.length > 0) {
  67175. this._postProcesses[0].autoClear = false;
  67176. }
  67177. };
  67178. /** @hidden */
  67179. RenderTargetTexture.prototype._shouldRender = function () {
  67180. if (this._currentRefreshId === -1) { // At least render once
  67181. this._currentRefreshId = 1;
  67182. return true;
  67183. }
  67184. if (this.refreshRate === this._currentRefreshId) {
  67185. this._currentRefreshId = 1;
  67186. return true;
  67187. }
  67188. this._currentRefreshId++;
  67189. return false;
  67190. };
  67191. RenderTargetTexture.prototype.getRenderSize = function () {
  67192. if (this._size.width) {
  67193. return this._size.width;
  67194. }
  67195. return this._size;
  67196. };
  67197. RenderTargetTexture.prototype.getRenderWidth = function () {
  67198. if (this._size.width) {
  67199. return this._size.width;
  67200. }
  67201. return this._size;
  67202. };
  67203. RenderTargetTexture.prototype.getRenderHeight = function () {
  67204. if (this._size.width) {
  67205. return this._size.height;
  67206. }
  67207. return this._size;
  67208. };
  67209. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67210. get: function () {
  67211. return true;
  67212. },
  67213. enumerable: true,
  67214. configurable: true
  67215. });
  67216. RenderTargetTexture.prototype.scale = function (ratio) {
  67217. var newSize = this.getRenderSize() * ratio;
  67218. this.resize(newSize);
  67219. };
  67220. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67221. if (this.isCube) {
  67222. return this._textureMatrix;
  67223. }
  67224. return _super.prototype.getReflectionTextureMatrix.call(this);
  67225. };
  67226. RenderTargetTexture.prototype.resize = function (size) {
  67227. this.releaseInternalTexture();
  67228. var scene = this.getScene();
  67229. if (!scene) {
  67230. return;
  67231. }
  67232. this._processSizeParameter(size);
  67233. if (this.isCube) {
  67234. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67235. }
  67236. else {
  67237. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  67238. }
  67239. };
  67240. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  67241. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  67242. if (dumpForDebug === void 0) { dumpForDebug = false; }
  67243. var scene = this.getScene();
  67244. if (!scene) {
  67245. return;
  67246. }
  67247. var engine = scene.getEngine();
  67248. if (this.useCameraPostProcesses !== undefined) {
  67249. useCameraPostProcess = this.useCameraPostProcesses;
  67250. }
  67251. if (this._waitingRenderList) {
  67252. this.renderList = [];
  67253. for (var index = 0; index < this._waitingRenderList.length; index++) {
  67254. var id = this._waitingRenderList[index];
  67255. var mesh_1 = scene.getMeshByID(id);
  67256. if (mesh_1) {
  67257. this.renderList.push(mesh_1);
  67258. }
  67259. }
  67260. delete this._waitingRenderList;
  67261. }
  67262. // Is predicate defined?
  67263. if (this.renderListPredicate) {
  67264. if (this.renderList) {
  67265. this.renderList.splice(0); // Clear previous renderList
  67266. }
  67267. else {
  67268. this.renderList = [];
  67269. }
  67270. var scene = this.getScene();
  67271. if (!scene) {
  67272. return;
  67273. }
  67274. var sceneMeshes = scene.meshes;
  67275. for (var index = 0; index < sceneMeshes.length; index++) {
  67276. var mesh = sceneMeshes[index];
  67277. if (this.renderListPredicate(mesh)) {
  67278. this.renderList.push(mesh);
  67279. }
  67280. }
  67281. }
  67282. this.onBeforeBindObservable.notifyObservers(this);
  67283. // Set custom projection.
  67284. // Needs to be before binding to prevent changing the aspect ratio.
  67285. var camera;
  67286. if (this.activeCamera) {
  67287. camera = this.activeCamera;
  67288. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67289. if (this.activeCamera !== scene.activeCamera) {
  67290. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67291. }
  67292. }
  67293. else {
  67294. camera = scene.activeCamera;
  67295. if (camera) {
  67296. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67297. }
  67298. }
  67299. // Prepare renderingManager
  67300. this._renderingManager.reset();
  67301. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67302. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67303. var sceneRenderId = scene.getRenderId();
  67304. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67305. var mesh = currentRenderList[meshIndex];
  67306. if (mesh) {
  67307. if (!mesh.isReady(this.refreshRate === 0)) {
  67308. this.resetRefreshCounter();
  67309. continue;
  67310. }
  67311. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67312. var isMasked = void 0;
  67313. if (!this.renderList && camera) {
  67314. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67315. }
  67316. else {
  67317. isMasked = false;
  67318. }
  67319. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67320. mesh._activate(sceneRenderId);
  67321. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67322. var subMesh = mesh.subMeshes[subIndex];
  67323. scene._activeIndices.addCount(subMesh.indexCount, false);
  67324. this._renderingManager.dispatch(subMesh, mesh);
  67325. }
  67326. }
  67327. }
  67328. }
  67329. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67330. var particleSystem = scene.particleSystems[particleIndex];
  67331. var emitter = particleSystem.emitter;
  67332. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67333. continue;
  67334. }
  67335. if (currentRenderList.indexOf(emitter) >= 0) {
  67336. this._renderingManager.dispatchParticles(particleSystem);
  67337. }
  67338. }
  67339. if (this.isCube) {
  67340. for (var face = 0; face < 6; face++) {
  67341. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67342. scene.incrementRenderId();
  67343. scene.resetCachedMaterial();
  67344. }
  67345. }
  67346. else {
  67347. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67348. }
  67349. this.onAfterUnbindObservable.notifyObservers(this);
  67350. if (scene.activeCamera) {
  67351. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67352. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67353. }
  67354. engine.setViewport(scene.activeCamera.viewport);
  67355. }
  67356. scene.resetCachedMaterial();
  67357. };
  67358. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67359. var minimum = 128;
  67360. var x = renderDimension * scale;
  67361. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67362. // Ensure we don't exceed the render dimension (while staying POT)
  67363. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67364. };
  67365. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67366. var _this = this;
  67367. if (!this._texture) {
  67368. return;
  67369. }
  67370. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67371. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67372. });
  67373. };
  67374. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67375. var scene = this.getScene();
  67376. if (!scene) {
  67377. return;
  67378. }
  67379. var engine = scene.getEngine();
  67380. if (!this._texture) {
  67381. return;
  67382. }
  67383. // Bind
  67384. if (this._postProcessManager) {
  67385. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67386. }
  67387. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67388. if (this._texture) {
  67389. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67390. }
  67391. }
  67392. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67393. // Clear
  67394. if (this.onClearObservable.hasObservers()) {
  67395. this.onClearObservable.notifyObservers(engine);
  67396. }
  67397. else {
  67398. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67399. }
  67400. if (!this._doNotChangeAspectRatio) {
  67401. scene.updateTransformMatrix(true);
  67402. }
  67403. // Render
  67404. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67405. if (this._postProcessManager) {
  67406. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67407. }
  67408. else if (useCameraPostProcess) {
  67409. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67410. }
  67411. if (!this._doNotChangeAspectRatio) {
  67412. scene.updateTransformMatrix(true);
  67413. }
  67414. // Dump ?
  67415. if (dumpForDebug) {
  67416. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67417. }
  67418. // Unbind
  67419. if (!this.isCube || faceIndex === 5) {
  67420. if (this.isCube) {
  67421. if (faceIndex === 5) {
  67422. engine.generateMipMapsForCubemap(this._texture);
  67423. }
  67424. }
  67425. this.unbindFrameBuffer(engine, faceIndex);
  67426. }
  67427. else {
  67428. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67429. }
  67430. };
  67431. /**
  67432. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67433. * This allowed control for front to back rendering or reversly depending of the special needs.
  67434. *
  67435. * @param renderingGroupId The rendering group id corresponding to its index
  67436. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67437. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67438. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67439. */
  67440. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67441. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67442. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67443. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67444. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67445. };
  67446. /**
  67447. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67448. *
  67449. * @param renderingGroupId The rendering group id corresponding to its index
  67450. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67451. */
  67452. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67453. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67454. this._renderingManager._useSceneAutoClearSetup = false;
  67455. };
  67456. RenderTargetTexture.prototype.clone = function () {
  67457. var textureSize = this.getSize();
  67458. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  67459. // Base texture
  67460. newTexture.hasAlpha = this.hasAlpha;
  67461. newTexture.level = this.level;
  67462. // RenderTarget Texture
  67463. newTexture.coordinatesMode = this.coordinatesMode;
  67464. if (this.renderList) {
  67465. newTexture.renderList = this.renderList.slice(0);
  67466. }
  67467. return newTexture;
  67468. };
  67469. RenderTargetTexture.prototype.serialize = function () {
  67470. if (!this.name) {
  67471. return null;
  67472. }
  67473. var serializationObject = _super.prototype.serialize.call(this);
  67474. serializationObject.renderTargetSize = this.getRenderSize();
  67475. serializationObject.renderList = [];
  67476. if (this.renderList) {
  67477. for (var index = 0; index < this.renderList.length; index++) {
  67478. serializationObject.renderList.push(this.renderList[index].id);
  67479. }
  67480. }
  67481. return serializationObject;
  67482. };
  67483. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67484. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67485. var objBuffer = this.getInternalTexture();
  67486. var scene = this.getScene();
  67487. if (objBuffer && scene) {
  67488. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67489. }
  67490. };
  67491. RenderTargetTexture.prototype.dispose = function () {
  67492. if (this._postProcessManager) {
  67493. this._postProcessManager.dispose();
  67494. this._postProcessManager = null;
  67495. }
  67496. this.clearPostProcesses(true);
  67497. if (this._resizeObserver) {
  67498. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67499. this._resizeObserver = null;
  67500. }
  67501. this.renderList = null;
  67502. // Remove from custom render targets
  67503. var scene = this.getScene();
  67504. if (!scene) {
  67505. return;
  67506. }
  67507. var index = scene.customRenderTargets.indexOf(this);
  67508. if (index >= 0) {
  67509. scene.customRenderTargets.splice(index, 1);
  67510. }
  67511. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67512. var camera = _a[_i];
  67513. index = camera.customRenderTargets.indexOf(this);
  67514. if (index >= 0) {
  67515. camera.customRenderTargets.splice(index, 1);
  67516. }
  67517. }
  67518. _super.prototype.dispose.call(this);
  67519. };
  67520. /** @hidden */
  67521. RenderTargetTexture.prototype._rebuild = function () {
  67522. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67523. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67524. }
  67525. if (this._postProcessManager) {
  67526. this._postProcessManager._rebuild();
  67527. }
  67528. };
  67529. /**
  67530. * Clear the info related to rendering groups preventing retention point in material dispose.
  67531. */
  67532. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67533. if (this._renderingManager) {
  67534. this._renderingManager.freeRenderingGroups();
  67535. }
  67536. };
  67537. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67538. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67539. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67540. return RenderTargetTexture;
  67541. }(BABYLON.Texture));
  67542. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67543. })(BABYLON || (BABYLON = {}));
  67544. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67545. var BABYLON;
  67546. (function (BABYLON) {
  67547. ;
  67548. var MultiRenderTarget = /** @class */ (function (_super) {
  67549. __extends(MultiRenderTarget, _super);
  67550. function MultiRenderTarget(name, size, count, scene, options) {
  67551. var _this = this;
  67552. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67553. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67554. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67555. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67556. _this._engine = scene.getEngine();
  67557. if (!_this.isSupported) {
  67558. _this.dispose();
  67559. return;
  67560. }
  67561. var types = [];
  67562. var samplingModes = [];
  67563. for (var i = 0; i < count; i++) {
  67564. if (options && options.types && options.types[i] !== undefined) {
  67565. types.push(options.types[i]);
  67566. }
  67567. else {
  67568. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67569. }
  67570. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67571. samplingModes.push(options.samplingModes[i]);
  67572. }
  67573. else {
  67574. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67575. }
  67576. }
  67577. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67578. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67579. _this._size = size;
  67580. _this._multiRenderTargetOptions = {
  67581. samplingModes: samplingModes,
  67582. generateMipMaps: generateMipMaps,
  67583. generateDepthBuffer: generateDepthBuffer,
  67584. generateStencilBuffer: generateStencilBuffer,
  67585. generateDepthTexture: generateDepthTexture,
  67586. types: types,
  67587. textureCount: count
  67588. };
  67589. _this._createInternalTextures();
  67590. _this._createTextures();
  67591. return _this;
  67592. }
  67593. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67594. get: function () {
  67595. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67596. },
  67597. enumerable: true,
  67598. configurable: true
  67599. });
  67600. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67601. get: function () {
  67602. return this._textures;
  67603. },
  67604. enumerable: true,
  67605. configurable: true
  67606. });
  67607. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67608. get: function () {
  67609. return this._textures[this._textures.length - 1];
  67610. },
  67611. enumerable: true,
  67612. configurable: true
  67613. });
  67614. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67615. set: function (wrap) {
  67616. if (this._textures) {
  67617. for (var i = 0; i < this._textures.length; i++) {
  67618. this._textures[i].wrapU = wrap;
  67619. }
  67620. }
  67621. },
  67622. enumerable: true,
  67623. configurable: true
  67624. });
  67625. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67626. set: function (wrap) {
  67627. if (this._textures) {
  67628. for (var i = 0; i < this._textures.length; i++) {
  67629. this._textures[i].wrapV = wrap;
  67630. }
  67631. }
  67632. },
  67633. enumerable: true,
  67634. configurable: true
  67635. });
  67636. /** @hidden */
  67637. MultiRenderTarget.prototype._rebuild = function () {
  67638. this.releaseInternalTextures();
  67639. this._createInternalTextures();
  67640. for (var i = 0; i < this._internalTextures.length; i++) {
  67641. var texture = this._textures[i];
  67642. texture._texture = this._internalTextures[i];
  67643. }
  67644. // Keeps references to frame buffer and stencil/depth buffer
  67645. this._texture = this._internalTextures[0];
  67646. };
  67647. MultiRenderTarget.prototype._createInternalTextures = function () {
  67648. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67649. };
  67650. MultiRenderTarget.prototype._createTextures = function () {
  67651. this._textures = [];
  67652. for (var i = 0; i < this._internalTextures.length; i++) {
  67653. var texture = new BABYLON.Texture(null, this.getScene());
  67654. texture._texture = this._internalTextures[i];
  67655. this._textures.push(texture);
  67656. }
  67657. // Keeps references to frame buffer and stencil/depth buffer
  67658. this._texture = this._internalTextures[0];
  67659. };
  67660. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67661. get: function () {
  67662. return this._samples;
  67663. },
  67664. set: function (value) {
  67665. if (this._samples === value) {
  67666. return;
  67667. }
  67668. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67669. },
  67670. enumerable: true,
  67671. configurable: true
  67672. });
  67673. MultiRenderTarget.prototype.resize = function (size) {
  67674. this.releaseInternalTextures();
  67675. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67676. this._createInternalTextures();
  67677. };
  67678. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67679. var _this = this;
  67680. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67681. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67682. });
  67683. };
  67684. MultiRenderTarget.prototype.dispose = function () {
  67685. this.releaseInternalTextures();
  67686. _super.prototype.dispose.call(this);
  67687. };
  67688. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67689. if (!this._internalTextures) {
  67690. return;
  67691. }
  67692. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67693. if (this._internalTextures[i] !== undefined) {
  67694. this._internalTextures[i].dispose();
  67695. this._internalTextures.splice(i, 1);
  67696. }
  67697. }
  67698. };
  67699. return MultiRenderTarget;
  67700. }(BABYLON.RenderTargetTexture));
  67701. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67702. })(BABYLON || (BABYLON = {}));
  67703. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67704. var BABYLON;
  67705. (function (BABYLON) {
  67706. var MirrorTexture = /** @class */ (function (_super) {
  67707. __extends(MirrorTexture, _super);
  67708. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67709. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67711. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67712. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67713. _this.scene = scene;
  67714. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67715. _this._transformMatrix = BABYLON.Matrix.Zero();
  67716. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67717. _this._adaptiveBlurKernel = 0;
  67718. _this._blurKernelX = 0;
  67719. _this._blurKernelY = 0;
  67720. _this._blurRatio = 1.0;
  67721. _this.ignoreCameraViewport = true;
  67722. _this._updateGammaSpace();
  67723. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67724. _this._updateGammaSpace;
  67725. });
  67726. _this.onBeforeRenderObservable.add(function () {
  67727. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67728. _this._savedViewMatrix = scene.getViewMatrix();
  67729. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67730. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67731. scene.clipPlane = _this.mirrorPlane;
  67732. scene.getEngine().cullBackFaces = false;
  67733. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67734. });
  67735. _this.onAfterRenderObservable.add(function () {
  67736. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67737. scene.getEngine().cullBackFaces = true;
  67738. scene._mirroredCameraPosition = null;
  67739. delete scene.clipPlane;
  67740. });
  67741. return _this;
  67742. }
  67743. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67744. get: function () {
  67745. return this._blurRatio;
  67746. },
  67747. set: function (value) {
  67748. if (this._blurRatio === value) {
  67749. return;
  67750. }
  67751. this._blurRatio = value;
  67752. this._preparePostProcesses();
  67753. },
  67754. enumerable: true,
  67755. configurable: true
  67756. });
  67757. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67758. set: function (value) {
  67759. this._adaptiveBlurKernel = value;
  67760. this._autoComputeBlurKernel();
  67761. },
  67762. enumerable: true,
  67763. configurable: true
  67764. });
  67765. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67766. set: function (value) {
  67767. this.blurKernelX = value;
  67768. this.blurKernelY = value;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67774. get: function () {
  67775. return this._blurKernelX;
  67776. },
  67777. set: function (value) {
  67778. if (this._blurKernelX === value) {
  67779. return;
  67780. }
  67781. this._blurKernelX = value;
  67782. this._preparePostProcesses();
  67783. },
  67784. enumerable: true,
  67785. configurable: true
  67786. });
  67787. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67788. get: function () {
  67789. return this._blurKernelY;
  67790. },
  67791. set: function (value) {
  67792. if (this._blurKernelY === value) {
  67793. return;
  67794. }
  67795. this._blurKernelY = value;
  67796. this._preparePostProcesses();
  67797. },
  67798. enumerable: true,
  67799. configurable: true
  67800. });
  67801. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67802. var engine = this.getScene().getEngine();
  67803. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67804. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67805. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67806. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67807. };
  67808. MirrorTexture.prototype._onRatioRescale = function () {
  67809. if (this._sizeRatio) {
  67810. this.resize(this._initialSizeParameter);
  67811. if (!this._adaptiveBlurKernel) {
  67812. this._preparePostProcesses();
  67813. }
  67814. }
  67815. if (this._adaptiveBlurKernel) {
  67816. this._autoComputeBlurKernel();
  67817. }
  67818. };
  67819. MirrorTexture.prototype._updateGammaSpace = function () {
  67820. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67821. };
  67822. MirrorTexture.prototype._preparePostProcesses = function () {
  67823. this.clearPostProcesses(true);
  67824. if (this._blurKernelX && this._blurKernelY) {
  67825. var engine = this.getScene().getEngine();
  67826. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67827. 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);
  67828. this._blurX.autoClear = false;
  67829. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67830. this._blurX.inputTexture = this._texture;
  67831. }
  67832. else {
  67833. this._blurX.alwaysForcePOT = true;
  67834. }
  67835. 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);
  67836. this._blurY.autoClear = false;
  67837. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67838. this.addPostProcess(this._blurX);
  67839. this.addPostProcess(this._blurY);
  67840. }
  67841. else {
  67842. if (this._blurY) {
  67843. this.removePostProcess(this._blurY);
  67844. this._blurY.dispose();
  67845. this._blurY = null;
  67846. }
  67847. if (this._blurX) {
  67848. this.removePostProcess(this._blurX);
  67849. this._blurX.dispose();
  67850. this._blurX = null;
  67851. }
  67852. }
  67853. };
  67854. MirrorTexture.prototype.clone = function () {
  67855. var scene = this.getScene();
  67856. if (!scene) {
  67857. return this;
  67858. }
  67859. var textureSize = this.getSize();
  67860. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67861. // Base texture
  67862. newTexture.hasAlpha = this.hasAlpha;
  67863. newTexture.level = this.level;
  67864. // Mirror Texture
  67865. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67866. if (this.renderList) {
  67867. newTexture.renderList = this.renderList.slice(0);
  67868. }
  67869. return newTexture;
  67870. };
  67871. MirrorTexture.prototype.serialize = function () {
  67872. if (!this.name) {
  67873. return null;
  67874. }
  67875. var serializationObject = _super.prototype.serialize.call(this);
  67876. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67877. return serializationObject;
  67878. };
  67879. MirrorTexture.prototype.dispose = function () {
  67880. _super.prototype.dispose.call(this);
  67881. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67882. };
  67883. return MirrorTexture;
  67884. }(BABYLON.RenderTargetTexture));
  67885. BABYLON.MirrorTexture = MirrorTexture;
  67886. })(BABYLON || (BABYLON = {}));
  67887. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67888. var BABYLON;
  67889. (function (BABYLON) {
  67890. /**
  67891. * Creates a refraction texture used by refraction channel of the standard material.
  67892. * @param name the texture name
  67893. * @param size size of the underlying texture
  67894. * @param scene root scene
  67895. */
  67896. var RefractionTexture = /** @class */ (function (_super) {
  67897. __extends(RefractionTexture, _super);
  67898. function RefractionTexture(name, size, scene, generateMipMaps) {
  67899. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67900. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67901. _this.depth = 2.0;
  67902. _this.onBeforeRenderObservable.add(function () {
  67903. scene.clipPlane = _this.refractionPlane;
  67904. });
  67905. _this.onAfterRenderObservable.add(function () {
  67906. delete scene.clipPlane;
  67907. });
  67908. return _this;
  67909. }
  67910. RefractionTexture.prototype.clone = function () {
  67911. var scene = this.getScene();
  67912. if (!scene) {
  67913. return this;
  67914. }
  67915. var textureSize = this.getSize();
  67916. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67917. // Base texture
  67918. newTexture.hasAlpha = this.hasAlpha;
  67919. newTexture.level = this.level;
  67920. // Refraction Texture
  67921. newTexture.refractionPlane = this.refractionPlane.clone();
  67922. if (this.renderList) {
  67923. newTexture.renderList = this.renderList.slice(0);
  67924. }
  67925. newTexture.depth = this.depth;
  67926. return newTexture;
  67927. };
  67928. RefractionTexture.prototype.serialize = function () {
  67929. if (!this.name) {
  67930. return null;
  67931. }
  67932. var serializationObject = _super.prototype.serialize.call(this);
  67933. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67934. serializationObject.depth = this.depth;
  67935. return serializationObject;
  67936. };
  67937. return RefractionTexture;
  67938. }(BABYLON.RenderTargetTexture));
  67939. BABYLON.RefractionTexture = RefractionTexture;
  67940. })(BABYLON || (BABYLON = {}));
  67941. //# sourceMappingURL=babylon.refractionTexture.js.map
  67942. var BABYLON;
  67943. (function (BABYLON) {
  67944. /**
  67945. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67946. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67947. */
  67948. var DynamicTexture = /** @class */ (function (_super) {
  67949. __extends(DynamicTexture, _super);
  67950. /**
  67951. * Creates a {BABYLON.DynamicTexture}
  67952. * @param name defines the name of the texture
  67953. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  67954. * @param scene defines the scene where you want the texture
  67955. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67956. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67957. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67958. */
  67959. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67960. if (scene === void 0) { scene = null; }
  67961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67962. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67963. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67964. _this.name = name;
  67965. _this._engine = _this.getScene().getEngine();
  67966. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67967. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67968. _this._generateMipMaps = generateMipMaps;
  67969. if (options.getContext) {
  67970. _this._canvas = options;
  67971. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67972. }
  67973. else {
  67974. _this._canvas = document.createElement("canvas");
  67975. if (options.width || options.width === 0) {
  67976. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67977. }
  67978. else {
  67979. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67980. }
  67981. }
  67982. var textureSize = _this.getSize();
  67983. _this._canvas.width = textureSize.width;
  67984. _this._canvas.height = textureSize.height;
  67985. _this._context = _this._canvas.getContext("2d");
  67986. return _this;
  67987. }
  67988. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67989. /**
  67990. * Gets the current state of canRescale
  67991. */
  67992. get: function () {
  67993. return true;
  67994. },
  67995. enumerable: true,
  67996. configurable: true
  67997. });
  67998. DynamicTexture.prototype._recreate = function (textureSize) {
  67999. this._canvas.width = textureSize.width;
  68000. this._canvas.height = textureSize.height;
  68001. this.releaseInternalTexture();
  68002. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68003. };
  68004. /**
  68005. * Scales the texture
  68006. * @param ratio the scale factor to apply to both width and height
  68007. */
  68008. DynamicTexture.prototype.scale = function (ratio) {
  68009. var textureSize = this.getSize();
  68010. textureSize.width *= ratio;
  68011. textureSize.height *= ratio;
  68012. this._recreate(textureSize);
  68013. };
  68014. /**
  68015. * Resizes the texture
  68016. * @param width the new width
  68017. * @param height the new height
  68018. */
  68019. DynamicTexture.prototype.scaleTo = function (width, height) {
  68020. var textureSize = this.getSize();
  68021. textureSize.width = width;
  68022. textureSize.height = height;
  68023. this._recreate(textureSize);
  68024. };
  68025. /**
  68026. * Gets the context of the canvas used by the texture
  68027. * @returns the canvas context of the dynamic texture
  68028. */
  68029. DynamicTexture.prototype.getContext = function () {
  68030. return this._context;
  68031. };
  68032. /**
  68033. * Clears the texture
  68034. */
  68035. DynamicTexture.prototype.clear = function () {
  68036. var size = this.getSize();
  68037. this._context.fillRect(0, 0, size.width, size.height);
  68038. };
  68039. /**
  68040. * Updates the texture
  68041. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68042. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68043. */
  68044. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68045. if (premulAlpha === void 0) { premulAlpha = false; }
  68046. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68047. };
  68048. /**
  68049. * Draws text onto the texture
  68050. * @param text defines the text to be drawn
  68051. * @param x defines the placement of the text from the left
  68052. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68053. * @param font defines the font to be used with font-style, font-size, font-name
  68054. * @param color defines the color used for the text
  68055. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68056. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68057. * @param update defines whether texture is immediately update (default is true)
  68058. */
  68059. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68060. if (update === void 0) { update = true; }
  68061. var size = this.getSize();
  68062. if (clearColor) {
  68063. this._context.fillStyle = clearColor;
  68064. this._context.fillRect(0, 0, size.width, size.height);
  68065. }
  68066. this._context.font = font;
  68067. if (x === null || x === undefined) {
  68068. var textSize = this._context.measureText(text);
  68069. x = (size.width - textSize.width) / 2;
  68070. }
  68071. if (y === null || y === undefined) {
  68072. var fontSize = parseInt((font.replace(/\D/g, '')));
  68073. y = (size.height / 2) + (fontSize / 3.65);
  68074. }
  68075. this._context.fillStyle = color;
  68076. this._context.fillText(text, x, y);
  68077. if (update) {
  68078. this.update(invertY);
  68079. }
  68080. };
  68081. /**
  68082. * Clones the texture
  68083. * @returns the clone of the texture.
  68084. */
  68085. DynamicTexture.prototype.clone = function () {
  68086. var scene = this.getScene();
  68087. if (!scene) {
  68088. return this;
  68089. }
  68090. var textureSize = this.getSize();
  68091. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68092. // Base texture
  68093. newTexture.hasAlpha = this.hasAlpha;
  68094. newTexture.level = this.level;
  68095. // Dynamic Texture
  68096. newTexture.wrapU = this.wrapU;
  68097. newTexture.wrapV = this.wrapV;
  68098. return newTexture;
  68099. };
  68100. /**
  68101. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68102. * @returns a serialized dynamic texture object
  68103. */
  68104. DynamicTexture.prototype.serialize = function () {
  68105. var scene = this.getScene();
  68106. if (scene && !scene.isReady()) {
  68107. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68108. }
  68109. var serializationObject = _super.prototype.serialize.call(this);
  68110. serializationObject.base64String = this._canvas.toDataURL();
  68111. serializationObject.invertY = this._invertY;
  68112. serializationObject.samplingMode = this.samplingMode;
  68113. return serializationObject;
  68114. };
  68115. /** @hidden */
  68116. DynamicTexture.prototype._rebuild = function () {
  68117. this.update();
  68118. };
  68119. return DynamicTexture;
  68120. }(BABYLON.Texture));
  68121. BABYLON.DynamicTexture = DynamicTexture;
  68122. })(BABYLON || (BABYLON = {}));
  68123. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68124. var BABYLON;
  68125. (function (BABYLON) {
  68126. var VideoTexture = /** @class */ (function (_super) {
  68127. __extends(VideoTexture, _super);
  68128. /**
  68129. * Creates a video texture.
  68130. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68131. * @param {string | null} name optional name, will detect from video source, if not defined
  68132. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68133. * @param {BABYLON.Scene} scene is obviously the current scene.
  68134. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68135. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68136. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68137. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68138. */
  68139. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68140. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68141. if (invertY === void 0) { invertY = false; }
  68142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68143. if (settings === void 0) { settings = {
  68144. autoPlay: true,
  68145. loop: true,
  68146. autoUpdateTexture: true,
  68147. }; }
  68148. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68149. _this._onUserActionRequestedObservable = null;
  68150. _this._stillImageCaptured = false;
  68151. _this._poster = false;
  68152. _this._createInternalTexture = function () {
  68153. if (_this._texture != null) {
  68154. if (_this._poster) {
  68155. _this._texture.dispose();
  68156. _this._poster = false;
  68157. }
  68158. else {
  68159. return;
  68160. }
  68161. }
  68162. if (!_this._engine.needPOTTextures ||
  68163. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68164. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68165. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68166. }
  68167. else {
  68168. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68169. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68170. _this._generateMipMaps = false;
  68171. }
  68172. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68173. if (!_this.video.autoplay) {
  68174. var oldHandler_1 = _this.video.onplaying;
  68175. var error_1 = false;
  68176. _this.video.onplaying = function () {
  68177. _this.video.onplaying = oldHandler_1;
  68178. _this._texture.isReady = true;
  68179. _this._updateInternalTexture();
  68180. if (!error_1) {
  68181. _this.video.pause();
  68182. }
  68183. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68184. _this.onLoadObservable.notifyObservers(_this);
  68185. }
  68186. };
  68187. var playing = _this.video.play();
  68188. if (playing) {
  68189. playing.then(function () {
  68190. // Everything is good.
  68191. })
  68192. .catch(function () {
  68193. error_1 = true;
  68194. // On Chrome for instance, new policies might prevent playing without user interaction.
  68195. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68196. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68197. }
  68198. });
  68199. }
  68200. else {
  68201. _this.video.onplaying = oldHandler_1;
  68202. _this._texture.isReady = true;
  68203. _this._updateInternalTexture();
  68204. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68205. _this.onLoadObservable.notifyObservers(_this);
  68206. }
  68207. }
  68208. }
  68209. else {
  68210. _this._texture.isReady = true;
  68211. _this._updateInternalTexture();
  68212. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68213. _this.onLoadObservable.notifyObservers(_this);
  68214. }
  68215. }
  68216. };
  68217. _this.reset = function () {
  68218. if (_this._texture == null) {
  68219. return;
  68220. }
  68221. if (!_this._poster) {
  68222. _this._texture.dispose();
  68223. _this._texture = null;
  68224. }
  68225. };
  68226. _this._updateInternalTexture = function (e) {
  68227. if (_this._texture == null || !_this._texture.isReady) {
  68228. return;
  68229. }
  68230. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68231. return;
  68232. }
  68233. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68234. };
  68235. _this._engine = _this.getScene().getEngine();
  68236. _this._generateMipMaps = generateMipMaps;
  68237. _this._samplingMode = samplingMode;
  68238. _this.autoUpdateTexture = settings.autoUpdateTexture;
  68239. _this.name = name || _this._getName(src);
  68240. _this.video = _this._getVideo(src);
  68241. if (settings.poster) {
  68242. _this.video.poster = settings.poster;
  68243. }
  68244. if (settings.autoPlay !== undefined) {
  68245. _this.video.autoplay = settings.autoPlay;
  68246. }
  68247. if (settings.loop !== undefined) {
  68248. _this.video.loop = settings.loop;
  68249. }
  68250. _this.video.setAttribute("playsinline", "");
  68251. _this.video.addEventListener("canplay", _this._createInternalTexture);
  68252. _this.video.addEventListener("paused", _this._updateInternalTexture);
  68253. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  68254. _this.video.addEventListener("emptied", _this.reset);
  68255. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  68256. _this._createInternalTexture();
  68257. }
  68258. if (settings.poster) {
  68259. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  68260. _this._poster = true;
  68261. }
  68262. return _this;
  68263. }
  68264. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  68265. get: function () {
  68266. if (!this._onUserActionRequestedObservable) {
  68267. this._onUserActionRequestedObservable = new BABYLON.Observable();
  68268. }
  68269. return this._onUserActionRequestedObservable;
  68270. },
  68271. enumerable: true,
  68272. configurable: true
  68273. });
  68274. VideoTexture.prototype._getName = function (src) {
  68275. if (src instanceof HTMLVideoElement) {
  68276. return src.currentSrc;
  68277. }
  68278. if (typeof src === "object") {
  68279. return src.toString();
  68280. }
  68281. return src;
  68282. };
  68283. ;
  68284. VideoTexture.prototype._getVideo = function (src) {
  68285. if (src instanceof HTMLVideoElement) {
  68286. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68287. return src;
  68288. }
  68289. var video = document.createElement("video");
  68290. if (typeof src === "string") {
  68291. BABYLON.Tools.SetCorsBehavior(src, video);
  68292. video.src = src;
  68293. }
  68294. else {
  68295. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68296. src.forEach(function (url) {
  68297. var source = document.createElement("source");
  68298. source.src = url;
  68299. video.appendChild(source);
  68300. });
  68301. }
  68302. return video;
  68303. };
  68304. ;
  68305. /**
  68306. * @hidden Internal method to initiate `update`.
  68307. */
  68308. VideoTexture.prototype._rebuild = function () {
  68309. this.update();
  68310. };
  68311. /**
  68312. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68313. */
  68314. VideoTexture.prototype.update = function () {
  68315. if (!this.autoUpdateTexture) {
  68316. // Expecting user to call `updateTexture` manually
  68317. return;
  68318. }
  68319. this.updateTexture(true);
  68320. };
  68321. /**
  68322. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68323. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68324. */
  68325. VideoTexture.prototype.updateTexture = function (isVisible) {
  68326. if (!isVisible) {
  68327. return;
  68328. }
  68329. if (this.video.paused && this._stillImageCaptured) {
  68330. return;
  68331. }
  68332. this._stillImageCaptured = true;
  68333. this._updateInternalTexture();
  68334. };
  68335. /**
  68336. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68337. * @param url New url.
  68338. */
  68339. VideoTexture.prototype.updateURL = function (url) {
  68340. this.video.src = url;
  68341. };
  68342. VideoTexture.prototype.dispose = function () {
  68343. _super.prototype.dispose.call(this);
  68344. if (this._onUserActionRequestedObservable) {
  68345. this._onUserActionRequestedObservable.clear();
  68346. this._onUserActionRequestedObservable = null;
  68347. }
  68348. this.video.removeEventListener("canplay", this._createInternalTexture);
  68349. this.video.removeEventListener("paused", this._updateInternalTexture);
  68350. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68351. this.video.removeEventListener("emptied", this.reset);
  68352. this.video.pause();
  68353. };
  68354. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68355. var video = document.createElement("video");
  68356. video.setAttribute('autoplay', '');
  68357. video.setAttribute('muted', '');
  68358. video.setAttribute('playsinline', '');
  68359. var constraintsDeviceId;
  68360. if (constraints && constraints.deviceId) {
  68361. constraintsDeviceId = {
  68362. exact: constraints.deviceId,
  68363. };
  68364. }
  68365. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68366. if (navigator.mediaDevices) {
  68367. navigator.mediaDevices.getUserMedia({ video: constraints })
  68368. .then(function (stream) {
  68369. if (video.mozSrcObject !== undefined) {
  68370. // hack for Firefox < 19
  68371. video.mozSrcObject = stream;
  68372. }
  68373. else {
  68374. video.srcObject = stream;
  68375. }
  68376. var onPlaying = function () {
  68377. if (onReady) {
  68378. onReady(new VideoTexture("video", video, scene, true, true));
  68379. }
  68380. video.removeEventListener("playing", onPlaying);
  68381. };
  68382. video.addEventListener("playing", onPlaying);
  68383. video.play();
  68384. })
  68385. .catch(function (err) {
  68386. BABYLON.Tools.Error(err.name);
  68387. });
  68388. }
  68389. else {
  68390. navigator.getUserMedia =
  68391. navigator.getUserMedia ||
  68392. navigator.webkitGetUserMedia ||
  68393. navigator.mozGetUserMedia ||
  68394. navigator.msGetUserMedia;
  68395. if (navigator.getUserMedia) {
  68396. navigator.getUserMedia({
  68397. video: {
  68398. deviceId: constraintsDeviceId,
  68399. width: {
  68400. min: (constraints && constraints.minWidth) || 256,
  68401. max: (constraints && constraints.maxWidth) || 640,
  68402. },
  68403. height: {
  68404. min: (constraints && constraints.minHeight) || 256,
  68405. max: (constraints && constraints.maxHeight) || 480,
  68406. },
  68407. },
  68408. }, function (stream) {
  68409. if (video.mozSrcObject !== undefined) {
  68410. // hack for Firefox < 19
  68411. video.mozSrcObject = stream;
  68412. }
  68413. else {
  68414. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68415. }
  68416. video.play();
  68417. if (onReady) {
  68418. onReady(new VideoTexture("video", video, scene, true, true));
  68419. }
  68420. }, function (e) {
  68421. BABYLON.Tools.Error(e.name);
  68422. });
  68423. }
  68424. }
  68425. };
  68426. return VideoTexture;
  68427. }(BABYLON.Texture));
  68428. BABYLON.VideoTexture = VideoTexture;
  68429. })(BABYLON || (BABYLON = {}));
  68430. //# sourceMappingURL=babylon.videoTexture.js.map
  68431. var BABYLON;
  68432. (function (BABYLON) {
  68433. var RawTexture = /** @class */ (function (_super) {
  68434. __extends(RawTexture, _super);
  68435. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68436. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68437. if (invertY === void 0) { invertY = false; }
  68438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68439. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68440. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68441. _this.format = format;
  68442. _this._engine = scene.getEngine();
  68443. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68444. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68445. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68446. return _this;
  68447. }
  68448. RawTexture.prototype.update = function (data) {
  68449. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68450. };
  68451. // Statics
  68452. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68453. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68454. if (invertY === void 0) { invertY = false; }
  68455. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68456. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68457. };
  68458. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68459. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68460. if (invertY === void 0) { invertY = false; }
  68461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68462. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68463. };
  68464. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68465. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68466. if (invertY === void 0) { invertY = false; }
  68467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68468. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68469. };
  68470. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68471. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68472. if (invertY === void 0) { invertY = false; }
  68473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68474. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68475. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68476. };
  68477. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68478. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68479. if (invertY === void 0) { invertY = false; }
  68480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68481. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68482. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68483. };
  68484. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68485. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68486. if (invertY === void 0) { invertY = false; }
  68487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68488. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68489. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68490. };
  68491. return RawTexture;
  68492. }(BABYLON.Texture));
  68493. BABYLON.RawTexture = RawTexture;
  68494. })(BABYLON || (BABYLON = {}));
  68495. //# sourceMappingURL=babylon.rawTexture.js.map
  68496. var BABYLON;
  68497. (function (BABYLON) {
  68498. /**
  68499. * Class used to store 3D textures containing user data
  68500. */
  68501. var RawTexture3D = /** @class */ (function (_super) {
  68502. __extends(RawTexture3D, _super);
  68503. /**
  68504. * Create a new RawTexture3D
  68505. * @param data defines the data of the texture
  68506. * @param width defines the width of the texture
  68507. * @param height defines the height of the texture
  68508. * @param depth defines the depth of the texture
  68509. * @param format defines the texture format to use
  68510. * @param scene defines the hosting scene
  68511. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68512. * @param invertY defines if texture must be stored with Y axis inverted
  68513. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68514. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68515. */
  68516. function RawTexture3D(data, width, height, depth,
  68517. /** Gets or sets the texture format to use */
  68518. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68519. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68520. if (invertY === void 0) { invertY = false; }
  68521. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68522. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68523. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68524. _this.format = format;
  68525. _this._engine = scene.getEngine();
  68526. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68527. _this.is3D = true;
  68528. return _this;
  68529. }
  68530. /**
  68531. * Update the texture with new data
  68532. * @param data defines the data to store in the texture
  68533. */
  68534. RawTexture3D.prototype.update = function (data) {
  68535. if (!this._texture) {
  68536. return;
  68537. }
  68538. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68539. };
  68540. return RawTexture3D;
  68541. }(BABYLON.Texture));
  68542. BABYLON.RawTexture3D = RawTexture3D;
  68543. })(BABYLON || (BABYLON = {}));
  68544. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68545. var BABYLON;
  68546. (function (BABYLON) {
  68547. /**
  68548. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68549. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68550. */
  68551. var PostProcessManager = /** @class */ (function () {
  68552. /**
  68553. * Creates a new instance PostProcess
  68554. * @param scene The scene that the post process is associated with.
  68555. */
  68556. function PostProcessManager(scene) {
  68557. this._vertexBuffers = {};
  68558. this._scene = scene;
  68559. }
  68560. PostProcessManager.prototype._prepareBuffers = function () {
  68561. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68562. return;
  68563. }
  68564. // VBO
  68565. var vertices = [];
  68566. vertices.push(1, 1);
  68567. vertices.push(-1, 1);
  68568. vertices.push(-1, -1);
  68569. vertices.push(1, -1);
  68570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68571. this._buildIndexBuffer();
  68572. };
  68573. PostProcessManager.prototype._buildIndexBuffer = function () {
  68574. // Indices
  68575. var indices = [];
  68576. indices.push(0);
  68577. indices.push(1);
  68578. indices.push(2);
  68579. indices.push(0);
  68580. indices.push(2);
  68581. indices.push(3);
  68582. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68583. };
  68584. /**
  68585. * Rebuilds the vertex buffers of the manager.
  68586. * @hidden
  68587. */
  68588. PostProcessManager.prototype._rebuild = function () {
  68589. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68590. if (!vb) {
  68591. return;
  68592. }
  68593. vb._rebuild();
  68594. this._buildIndexBuffer();
  68595. };
  68596. // Methods
  68597. /**
  68598. * Prepares a frame to be run through a post process.
  68599. * @param sourceTexture The input texture to the post procesess. (default: null)
  68600. * @param postProcesses An array of post processes to be run. (default: null)
  68601. * @returns True if the post processes were able to be run.
  68602. * @hidden
  68603. */
  68604. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68605. if (sourceTexture === void 0) { sourceTexture = null; }
  68606. if (postProcesses === void 0) { postProcesses = null; }
  68607. var camera = this._scene.activeCamera;
  68608. if (!camera) {
  68609. return false;
  68610. }
  68611. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68612. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68613. return false;
  68614. }
  68615. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68616. return true;
  68617. };
  68618. /**
  68619. * Manually render a set of post processes to a texture.
  68620. * @param postProcesses An array of post processes to be run.
  68621. * @param targetTexture The target texture to render to.
  68622. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68623. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68624. * @param lodLevel defines which lod of the texture to render to
  68625. */
  68626. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68627. if (targetTexture === void 0) { targetTexture = null; }
  68628. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68629. if (faceIndex === void 0) { faceIndex = 0; }
  68630. if (lodLevel === void 0) { lodLevel = 0; }
  68631. var engine = this._scene.getEngine();
  68632. for (var index = 0; index < postProcesses.length; index++) {
  68633. if (index < postProcesses.length - 1) {
  68634. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68635. }
  68636. else {
  68637. if (targetTexture) {
  68638. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68639. }
  68640. else {
  68641. engine.restoreDefaultFramebuffer();
  68642. }
  68643. }
  68644. var pp = postProcesses[index];
  68645. var effect = pp.apply();
  68646. if (effect) {
  68647. pp.onBeforeRenderObservable.notifyObservers(effect);
  68648. // VBOs
  68649. this._prepareBuffers();
  68650. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68651. // Draw order
  68652. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68653. pp.onAfterRenderObservable.notifyObservers(effect);
  68654. }
  68655. }
  68656. // Restore depth buffer
  68657. engine.setDepthBuffer(true);
  68658. engine.setDepthWrite(true);
  68659. };
  68660. /**
  68661. * Finalize the result of the output of the postprocesses.
  68662. * @param doNotPresent If true the result will not be displayed to the screen.
  68663. * @param targetTexture The target texture to render to.
  68664. * @param faceIndex The index of the face to bind the target texture to.
  68665. * @param postProcesses The array of post processes to render.
  68666. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68667. * @hidden
  68668. */
  68669. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68670. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68671. var camera = this._scene.activeCamera;
  68672. if (!camera) {
  68673. return;
  68674. }
  68675. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68676. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68677. return;
  68678. }
  68679. var engine = this._scene.getEngine();
  68680. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68681. var pp = postProcesses[index];
  68682. if (index < len - 1) {
  68683. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68684. }
  68685. else {
  68686. if (targetTexture) {
  68687. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68688. pp._outputTexture = targetTexture;
  68689. }
  68690. else {
  68691. engine.restoreDefaultFramebuffer();
  68692. pp._outputTexture = null;
  68693. }
  68694. }
  68695. if (doNotPresent) {
  68696. break;
  68697. }
  68698. var effect = pp.apply();
  68699. if (effect) {
  68700. pp.onBeforeRenderObservable.notifyObservers(effect);
  68701. // VBOs
  68702. this._prepareBuffers();
  68703. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68704. // Draw order
  68705. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68706. pp.onAfterRenderObservable.notifyObservers(effect);
  68707. }
  68708. }
  68709. // Restore states
  68710. engine.setDepthBuffer(true);
  68711. engine.setDepthWrite(true);
  68712. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68713. };
  68714. /**
  68715. * Disposes of the post process manager.
  68716. */
  68717. PostProcessManager.prototype.dispose = function () {
  68718. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68719. if (buffer) {
  68720. buffer.dispose();
  68721. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68722. }
  68723. if (this._indexBuffer) {
  68724. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68725. this._indexBuffer = null;
  68726. }
  68727. };
  68728. return PostProcessManager;
  68729. }());
  68730. BABYLON.PostProcessManager = PostProcessManager;
  68731. })(BABYLON || (BABYLON = {}));
  68732. //# sourceMappingURL=babylon.postProcessManager.js.map
  68733. var BABYLON;
  68734. (function (BABYLON) {
  68735. /**
  68736. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68737. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68738. */
  68739. var PostProcess = /** @class */ (function () {
  68740. /**
  68741. * Creates a new instance PostProcess
  68742. * @param name The name of the PostProcess.
  68743. * @param fragmentUrl The url of the fragment shader to be used.
  68744. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68745. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68746. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68747. * @param camera The camera to apply the render pass to.
  68748. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68749. * @param engine The engine which the post process will be applied. (default: current engine)
  68750. * @param reusable If the post process can be reused on the same frame. (default: false)
  68751. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68752. * @param textureType Type of textures used when performing the post process. (default: 0)
  68753. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68754. * @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
  68755. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68756. */
  68757. function PostProcess(
  68758. /** Name of the PostProcess. */
  68759. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68761. if (defines === void 0) { defines = null; }
  68762. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68763. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68764. if (blockCompilation === void 0) { blockCompilation = false; }
  68765. this.name = name;
  68766. /**
  68767. * Width of the texture to apply the post process on
  68768. */
  68769. this.width = -1;
  68770. /**
  68771. * Height of the texture to apply the post process on
  68772. */
  68773. this.height = -1;
  68774. /**
  68775. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68776. * @hidden
  68777. */
  68778. this._outputTexture = null;
  68779. /**
  68780. * If the buffer needs to be cleared before applying the post process. (default: true)
  68781. * Should be set to false if shader will overwrite all previous pixels.
  68782. */
  68783. this.autoClear = true;
  68784. /**
  68785. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68786. */
  68787. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68788. /**
  68789. * Animations to be used for the post processing
  68790. */
  68791. this.animations = new Array();
  68792. /**
  68793. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68794. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68795. */
  68796. this.enablePixelPerfectMode = false;
  68797. /**
  68798. * Force the postprocess to be applied without taking in account viewport
  68799. */
  68800. this.forceFullscreenViewport = true;
  68801. /**
  68802. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68803. *
  68804. * | Value | Type | Description |
  68805. * | ----- | ----------------------------------- | ----------- |
  68806. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68807. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68808. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68809. *
  68810. */
  68811. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68812. /**
  68813. * Force textures to be a power of two (default: false)
  68814. */
  68815. this.alwaysForcePOT = false;
  68816. this._samples = 1;
  68817. /**
  68818. * Modify the scale of the post process to be the same as the viewport (default: false)
  68819. */
  68820. this.adaptScaleToCurrentViewport = false;
  68821. this._reusable = false;
  68822. /**
  68823. * Smart array of input and output textures for the post process.
  68824. * @hidden
  68825. */
  68826. this._textures = new BABYLON.SmartArray(2);
  68827. /**
  68828. * The index in _textures that corresponds to the output texture.
  68829. * @hidden
  68830. */
  68831. this._currentRenderTextureInd = 0;
  68832. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68833. this._texelSize = BABYLON.Vector2.Zero();
  68834. // Events
  68835. /**
  68836. * An event triggered when the postprocess is activated.
  68837. */
  68838. this.onActivateObservable = new BABYLON.Observable();
  68839. /**
  68840. * An event triggered when the postprocess changes its size.
  68841. */
  68842. this.onSizeChangedObservable = new BABYLON.Observable();
  68843. /**
  68844. * An event triggered when the postprocess applies its effect.
  68845. */
  68846. this.onApplyObservable = new BABYLON.Observable();
  68847. /**
  68848. * An event triggered before rendering the postprocess
  68849. */
  68850. this.onBeforeRenderObservable = new BABYLON.Observable();
  68851. /**
  68852. * An event triggered after rendering the postprocess
  68853. */
  68854. this.onAfterRenderObservable = new BABYLON.Observable();
  68855. if (camera != null) {
  68856. this._camera = camera;
  68857. this._scene = camera.getScene();
  68858. camera.attachPostProcess(this);
  68859. this._engine = this._scene.getEngine();
  68860. this._scene.postProcesses.push(this);
  68861. }
  68862. else if (engine) {
  68863. this._engine = engine;
  68864. this._engine.postProcesses.push(this);
  68865. }
  68866. this._options = options;
  68867. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68868. this._reusable = reusable || false;
  68869. this._textureType = textureType;
  68870. this._samplers = samplers || [];
  68871. this._samplers.push("textureSampler");
  68872. this._fragmentUrl = fragmentUrl;
  68873. this._vertexUrl = vertexUrl;
  68874. this._parameters = parameters || [];
  68875. this._parameters.push("scale");
  68876. this._indexParameters = indexParameters;
  68877. if (!blockCompilation) {
  68878. this.updateEffect(defines);
  68879. }
  68880. }
  68881. Object.defineProperty(PostProcess.prototype, "samples", {
  68882. /**
  68883. * Number of sample textures (default: 1)
  68884. */
  68885. get: function () {
  68886. return this._samples;
  68887. },
  68888. set: function (n) {
  68889. var _this = this;
  68890. this._samples = n;
  68891. this._textures.forEach(function (texture) {
  68892. if (texture.samples !== _this._samples) {
  68893. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68894. }
  68895. });
  68896. },
  68897. enumerable: true,
  68898. configurable: true
  68899. });
  68900. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68901. /**
  68902. * A function that is added to the onActivateObservable
  68903. */
  68904. set: function (callback) {
  68905. if (this._onActivateObserver) {
  68906. this.onActivateObservable.remove(this._onActivateObserver);
  68907. }
  68908. if (callback) {
  68909. this._onActivateObserver = this.onActivateObservable.add(callback);
  68910. }
  68911. },
  68912. enumerable: true,
  68913. configurable: true
  68914. });
  68915. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68916. /**
  68917. * A function that is added to the onSizeChangedObservable
  68918. */
  68919. set: function (callback) {
  68920. if (this._onSizeChangedObserver) {
  68921. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68922. }
  68923. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68924. },
  68925. enumerable: true,
  68926. configurable: true
  68927. });
  68928. Object.defineProperty(PostProcess.prototype, "onApply", {
  68929. /**
  68930. * A function that is added to the onApplyObservable
  68931. */
  68932. set: function (callback) {
  68933. if (this._onApplyObserver) {
  68934. this.onApplyObservable.remove(this._onApplyObserver);
  68935. }
  68936. this._onApplyObserver = this.onApplyObservable.add(callback);
  68937. },
  68938. enumerable: true,
  68939. configurable: true
  68940. });
  68941. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68942. /**
  68943. * A function that is added to the onBeforeRenderObservable
  68944. */
  68945. set: function (callback) {
  68946. if (this._onBeforeRenderObserver) {
  68947. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68948. }
  68949. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68950. },
  68951. enumerable: true,
  68952. configurable: true
  68953. });
  68954. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68955. /**
  68956. * A function that is added to the onAfterRenderObservable
  68957. */
  68958. set: function (callback) {
  68959. if (this._onAfterRenderObserver) {
  68960. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68961. }
  68962. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68963. },
  68964. enumerable: true,
  68965. configurable: true
  68966. });
  68967. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68968. /**
  68969. * 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
  68970. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68971. */
  68972. get: function () {
  68973. return this._textures.data[this._currentRenderTextureInd];
  68974. },
  68975. set: function (value) {
  68976. this._forcedOutputTexture = value;
  68977. },
  68978. enumerable: true,
  68979. configurable: true
  68980. });
  68981. /**
  68982. * Gets the camera which post process is applied to.
  68983. * @returns The camera the post process is applied to.
  68984. */
  68985. PostProcess.prototype.getCamera = function () {
  68986. return this._camera;
  68987. };
  68988. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68989. /**
  68990. * Gets the texel size of the postprocess.
  68991. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68992. */
  68993. get: function () {
  68994. if (this._shareOutputWithPostProcess) {
  68995. return this._shareOutputWithPostProcess.texelSize;
  68996. }
  68997. if (this._forcedOutputTexture) {
  68998. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68999. }
  69000. return this._texelSize;
  69001. },
  69002. enumerable: true,
  69003. configurable: true
  69004. });
  69005. /**
  69006. * Gets the engine which this post process belongs to.
  69007. * @returns The engine the post process was enabled with.
  69008. */
  69009. PostProcess.prototype.getEngine = function () {
  69010. return this._engine;
  69011. };
  69012. /**
  69013. * The effect that is created when initializing the post process.
  69014. * @returns The created effect corrisponding the the postprocess.
  69015. */
  69016. PostProcess.prototype.getEffect = function () {
  69017. return this._effect;
  69018. };
  69019. /**
  69020. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69021. * @param postProcess The post process to share the output with.
  69022. * @returns This post process.
  69023. */
  69024. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69025. this._disposeTextures();
  69026. this._shareOutputWithPostProcess = postProcess;
  69027. return this;
  69028. };
  69029. /**
  69030. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69031. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69032. */
  69033. PostProcess.prototype.useOwnOutput = function () {
  69034. if (this._textures.length == 0) {
  69035. this._textures = new BABYLON.SmartArray(2);
  69036. }
  69037. this._shareOutputWithPostProcess = null;
  69038. };
  69039. /**
  69040. * Updates the effect with the current post process compile time values and recompiles the shader.
  69041. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69042. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69043. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69044. * @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
  69045. * @param onCompiled Called when the shader has been compiled.
  69046. * @param onError Called if there is an error when compiling a shader.
  69047. */
  69048. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69049. if (defines === void 0) { defines = null; }
  69050. if (uniforms === void 0) { uniforms = null; }
  69051. if (samplers === void 0) { samplers = null; }
  69052. 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);
  69053. };
  69054. /**
  69055. * The post process is reusable if it can be used multiple times within one frame.
  69056. * @returns If the post process is reusable
  69057. */
  69058. PostProcess.prototype.isReusable = function () {
  69059. return this._reusable;
  69060. };
  69061. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69062. PostProcess.prototype.markTextureDirty = function () {
  69063. this.width = -1;
  69064. };
  69065. /**
  69066. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69067. * 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.
  69068. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69069. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69070. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69071. * @returns The target texture that was bound to be written to.
  69072. */
  69073. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69074. var _this = this;
  69075. if (sourceTexture === void 0) { sourceTexture = null; }
  69076. camera = camera || this._camera;
  69077. var scene = camera.getScene();
  69078. var engine = scene.getEngine();
  69079. var maxSize = engine.getCaps().maxTextureSize;
  69080. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69081. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69082. // 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
  69083. var webVRCamera = camera.parent;
  69084. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69085. requiredWidth /= 2;
  69086. }
  69087. var desiredWidth = (this._options.width || requiredWidth);
  69088. var desiredHeight = this._options.height || requiredHeight;
  69089. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69090. if (this.adaptScaleToCurrentViewport) {
  69091. var currentViewport = engine.currentViewport;
  69092. if (currentViewport) {
  69093. desiredWidth *= currentViewport.width;
  69094. desiredHeight *= currentViewport.height;
  69095. }
  69096. }
  69097. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69098. if (!this._options.width) {
  69099. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69100. }
  69101. if (!this._options.height) {
  69102. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69103. }
  69104. }
  69105. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69106. if (this._textures.length > 0) {
  69107. for (var i = 0; i < this._textures.length; i++) {
  69108. this._engine._releaseTexture(this._textures.data[i]);
  69109. }
  69110. this._textures.reset();
  69111. }
  69112. this.width = desiredWidth;
  69113. this.height = desiredHeight;
  69114. var textureSize = { width: this.width, height: this.height };
  69115. var textureOptions = {
  69116. generateMipMaps: false,
  69117. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69118. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69119. samplingMode: this.renderTargetSamplingMode,
  69120. type: this._textureType
  69121. };
  69122. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69123. if (this._reusable) {
  69124. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69125. }
  69126. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69127. this.onSizeChangedObservable.notifyObservers(this);
  69128. }
  69129. this._textures.forEach(function (texture) {
  69130. if (texture.samples !== _this.samples) {
  69131. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69132. }
  69133. });
  69134. }
  69135. var target;
  69136. if (this._shareOutputWithPostProcess) {
  69137. target = this._shareOutputWithPostProcess.inputTexture;
  69138. }
  69139. else if (this._forcedOutputTexture) {
  69140. target = this._forcedOutputTexture;
  69141. this.width = this._forcedOutputTexture.width;
  69142. this.height = this._forcedOutputTexture.height;
  69143. }
  69144. else {
  69145. target = this.inputTexture;
  69146. }
  69147. // Bind the input of this post process to be used as the output of the previous post process.
  69148. if (this.enablePixelPerfectMode) {
  69149. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69150. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69151. }
  69152. else {
  69153. this._scaleRatio.copyFromFloats(1, 1);
  69154. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69155. }
  69156. this.onActivateObservable.notifyObservers(camera);
  69157. // Clear
  69158. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69159. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69160. }
  69161. if (this._reusable) {
  69162. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69163. }
  69164. return target;
  69165. };
  69166. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69167. /**
  69168. * If the post process is supported.
  69169. */
  69170. get: function () {
  69171. return this._effect.isSupported;
  69172. },
  69173. enumerable: true,
  69174. configurable: true
  69175. });
  69176. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69177. /**
  69178. * The aspect ratio of the output texture.
  69179. */
  69180. get: function () {
  69181. if (this._shareOutputWithPostProcess) {
  69182. return this._shareOutputWithPostProcess.aspectRatio;
  69183. }
  69184. if (this._forcedOutputTexture) {
  69185. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69186. }
  69187. return this.width / this.height;
  69188. },
  69189. enumerable: true,
  69190. configurable: true
  69191. });
  69192. /**
  69193. * Get a value indicating if the post-process is ready to be used
  69194. * @returns true if the post-process is ready (shader is compiled)
  69195. */
  69196. PostProcess.prototype.isReady = function () {
  69197. return this._effect && this._effect.isReady();
  69198. };
  69199. /**
  69200. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69201. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69202. */
  69203. PostProcess.prototype.apply = function () {
  69204. // Check
  69205. if (!this._effect || !this._effect.isReady())
  69206. return null;
  69207. // States
  69208. this._engine.enableEffect(this._effect);
  69209. this._engine.setState(false);
  69210. this._engine.setDepthBuffer(false);
  69211. this._engine.setDepthWrite(false);
  69212. // Alpha
  69213. this._engine.setAlphaMode(this.alphaMode);
  69214. if (this.alphaConstants) {
  69215. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69216. }
  69217. // Bind the output texture of the preivous post process as the input to this post process.
  69218. var source;
  69219. if (this._shareOutputWithPostProcess) {
  69220. source = this._shareOutputWithPostProcess.inputTexture;
  69221. }
  69222. else if (this._forcedOutputTexture) {
  69223. source = this._forcedOutputTexture;
  69224. }
  69225. else {
  69226. source = this.inputTexture;
  69227. }
  69228. this._effect._bindTexture("textureSampler", source);
  69229. // Parameters
  69230. this._effect.setVector2("scale", this._scaleRatio);
  69231. this.onApplyObservable.notifyObservers(this._effect);
  69232. return this._effect;
  69233. };
  69234. PostProcess.prototype._disposeTextures = function () {
  69235. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69236. return;
  69237. }
  69238. if (this._textures.length > 0) {
  69239. for (var i = 0; i < this._textures.length; i++) {
  69240. this._engine._releaseTexture(this._textures.data[i]);
  69241. }
  69242. }
  69243. this._textures.dispose();
  69244. };
  69245. /**
  69246. * Disposes the post process.
  69247. * @param camera The camera to dispose the post process on.
  69248. */
  69249. PostProcess.prototype.dispose = function (camera) {
  69250. camera = camera || this._camera;
  69251. this._disposeTextures();
  69252. if (this._scene) {
  69253. var index_1 = this._scene.postProcesses.indexOf(this);
  69254. if (index_1 !== -1) {
  69255. this._scene.postProcesses.splice(index_1, 1);
  69256. }
  69257. }
  69258. else {
  69259. var index_2 = this._engine.postProcesses.indexOf(this);
  69260. if (index_2 !== -1) {
  69261. this._engine.postProcesses.splice(index_2, 1);
  69262. }
  69263. }
  69264. if (!camera) {
  69265. return;
  69266. }
  69267. camera.detachPostProcess(this);
  69268. var index = camera._postProcesses.indexOf(this);
  69269. if (index === 0 && camera._postProcesses.length > 0) {
  69270. var firstPostProcess = this._camera._getFirstPostProcess();
  69271. if (firstPostProcess) {
  69272. firstPostProcess.markTextureDirty();
  69273. }
  69274. }
  69275. this.onActivateObservable.clear();
  69276. this.onAfterRenderObservable.clear();
  69277. this.onApplyObservable.clear();
  69278. this.onBeforeRenderObservable.clear();
  69279. this.onSizeChangedObservable.clear();
  69280. };
  69281. return PostProcess;
  69282. }());
  69283. BABYLON.PostProcess = PostProcess;
  69284. })(BABYLON || (BABYLON = {}));
  69285. //# sourceMappingURL=babylon.postProcess.js.map
  69286. var BABYLON;
  69287. (function (BABYLON) {
  69288. var PassPostProcess = /** @class */ (function (_super) {
  69289. __extends(PassPostProcess, _super);
  69290. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69291. if (camera === void 0) { camera = null; }
  69292. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69293. if (blockCompilation === void 0) { blockCompilation = false; }
  69294. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69295. }
  69296. return PassPostProcess;
  69297. }(BABYLON.PostProcess));
  69298. BABYLON.PassPostProcess = PassPostProcess;
  69299. })(BABYLON || (BABYLON = {}));
  69300. //# sourceMappingURL=babylon.passPostProcess.js.map
  69301. var __assign = (this && this.__assign) || function () {
  69302. __assign = Object.assign || function(t) {
  69303. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69304. s = arguments[i];
  69305. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69306. t[p] = s[p];
  69307. }
  69308. return t;
  69309. };
  69310. return __assign.apply(this, arguments);
  69311. };
  69312. var BABYLON;
  69313. (function (BABYLON) {
  69314. /**
  69315. * Default implementation IShadowGenerator.
  69316. * This is the main object responsible of generating shadows in the framework.
  69317. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69318. */
  69319. var ShadowGenerator = /** @class */ (function () {
  69320. /**
  69321. * Creates a ShadowGenerator object.
  69322. * A ShadowGenerator is the required tool to use the shadows.
  69323. * Each light casting shadows needs to use its own ShadowGenerator.
  69324. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69325. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69326. * @param light The light object generating the shadows.
  69327. * @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.
  69328. */
  69329. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69330. this._bias = 0.00005;
  69331. this._normalBias = 0;
  69332. this._blurBoxOffset = 1;
  69333. this._blurScale = 2;
  69334. this._blurKernel = 1;
  69335. this._useKernelBlur = false;
  69336. this._filter = ShadowGenerator.FILTER_NONE;
  69337. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69338. this._contactHardeningLightSizeUVRatio = 0.1;
  69339. this._darkness = 0;
  69340. this._transparencyShadow = false;
  69341. /**
  69342. * Controls the extent to which the shadows fade out at the edge of the frustum
  69343. * Used only by directionals and spots
  69344. */
  69345. this.frustumEdgeFalloff = 0;
  69346. /**
  69347. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69348. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69349. * It might on the other hand introduce peter panning.
  69350. */
  69351. this.forceBackFacesOnly = false;
  69352. this._lightDirection = BABYLON.Vector3.Zero();
  69353. this._viewMatrix = BABYLON.Matrix.Zero();
  69354. this._projectionMatrix = BABYLON.Matrix.Zero();
  69355. this._transformMatrix = BABYLON.Matrix.Zero();
  69356. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69357. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69358. this._currentFaceIndex = 0;
  69359. this._currentFaceIndexCache = 0;
  69360. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69361. this._mapSize = mapSize;
  69362. this._light = light;
  69363. this._scene = light.getScene();
  69364. light._shadowGenerator = this;
  69365. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  69366. if (!component) {
  69367. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  69368. this._scene._addComponent(component);
  69369. }
  69370. // Texture type fallback from float to int if not supported.
  69371. var caps = this._scene.getEngine().getCaps();
  69372. if (!useFullFloatFirst) {
  69373. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69374. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69375. }
  69376. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69377. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69378. }
  69379. else {
  69380. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69381. }
  69382. }
  69383. else {
  69384. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69385. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69386. }
  69387. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69388. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69389. }
  69390. else {
  69391. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69392. }
  69393. }
  69394. this._initializeGenerator();
  69395. this._applyFilterValues();
  69396. }
  69397. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69398. /**
  69399. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69400. */
  69401. get: function () {
  69402. return this._bias;
  69403. },
  69404. /**
  69405. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69406. */
  69407. set: function (bias) {
  69408. this._bias = bias;
  69409. },
  69410. enumerable: true,
  69411. configurable: true
  69412. });
  69413. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69414. /**
  69415. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69416. */
  69417. get: function () {
  69418. return this._normalBias;
  69419. },
  69420. /**
  69421. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69422. */
  69423. set: function (normalBias) {
  69424. this._normalBias = normalBias;
  69425. },
  69426. enumerable: true,
  69427. configurable: true
  69428. });
  69429. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69430. /**
  69431. * Gets the blur box offset: offset applied during the blur pass.
  69432. * Only usefull if useKernelBlur = false
  69433. */
  69434. get: function () {
  69435. return this._blurBoxOffset;
  69436. },
  69437. /**
  69438. * Sets the blur box offset: offset applied during the blur pass.
  69439. * Only usefull if useKernelBlur = false
  69440. */
  69441. set: function (value) {
  69442. if (this._blurBoxOffset === value) {
  69443. return;
  69444. }
  69445. this._blurBoxOffset = value;
  69446. this._disposeBlurPostProcesses();
  69447. },
  69448. enumerable: true,
  69449. configurable: true
  69450. });
  69451. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69452. /**
  69453. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69454. * 2 means half of the size.
  69455. */
  69456. get: function () {
  69457. return this._blurScale;
  69458. },
  69459. /**
  69460. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69461. * 2 means half of the size.
  69462. */
  69463. set: function (value) {
  69464. if (this._blurScale === value) {
  69465. return;
  69466. }
  69467. this._blurScale = value;
  69468. this._disposeBlurPostProcesses();
  69469. },
  69470. enumerable: true,
  69471. configurable: true
  69472. });
  69473. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69474. /**
  69475. * Gets the blur kernel: kernel size of the blur pass.
  69476. * Only usefull if useKernelBlur = true
  69477. */
  69478. get: function () {
  69479. return this._blurKernel;
  69480. },
  69481. /**
  69482. * Sets the blur kernel: kernel size of the blur pass.
  69483. * Only usefull if useKernelBlur = true
  69484. */
  69485. set: function (value) {
  69486. if (this._blurKernel === value) {
  69487. return;
  69488. }
  69489. this._blurKernel = value;
  69490. this._disposeBlurPostProcesses();
  69491. },
  69492. enumerable: true,
  69493. configurable: true
  69494. });
  69495. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69496. /**
  69497. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69498. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69499. */
  69500. get: function () {
  69501. return this._useKernelBlur;
  69502. },
  69503. /**
  69504. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69505. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69506. */
  69507. set: function (value) {
  69508. if (this._useKernelBlur === value) {
  69509. return;
  69510. }
  69511. this._useKernelBlur = value;
  69512. this._disposeBlurPostProcesses();
  69513. },
  69514. enumerable: true,
  69515. configurable: true
  69516. });
  69517. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69518. /**
  69519. * Gets the depth scale used in ESM mode.
  69520. */
  69521. get: function () {
  69522. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69523. },
  69524. /**
  69525. * Sets the depth scale used in ESM mode.
  69526. * This can override the scale stored on the light.
  69527. */
  69528. set: function (value) {
  69529. this._depthScale = value;
  69530. },
  69531. enumerable: true,
  69532. configurable: true
  69533. });
  69534. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69535. /**
  69536. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69537. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69538. */
  69539. get: function () {
  69540. return this._filter;
  69541. },
  69542. /**
  69543. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69544. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69545. */
  69546. set: function (value) {
  69547. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69548. if (this._light.needCube()) {
  69549. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69550. this.useExponentialShadowMap = true;
  69551. return;
  69552. }
  69553. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69554. this.useCloseExponentialShadowMap = true;
  69555. return;
  69556. }
  69557. // PCF on cubemap would also be expensive
  69558. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69559. this.usePoissonSampling = true;
  69560. return;
  69561. }
  69562. }
  69563. // Weblg1 fallback for PCF.
  69564. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69565. if (this._scene.getEngine().webGLVersion === 1) {
  69566. this.usePoissonSampling = true;
  69567. return;
  69568. }
  69569. }
  69570. if (this._filter === value) {
  69571. return;
  69572. }
  69573. this._filter = value;
  69574. this._disposeBlurPostProcesses();
  69575. this._applyFilterValues();
  69576. this._light._markMeshesAsLightDirty();
  69577. },
  69578. enumerable: true,
  69579. configurable: true
  69580. });
  69581. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69582. /**
  69583. * Gets if the current filter is set to Poisson Sampling.
  69584. */
  69585. get: function () {
  69586. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69587. },
  69588. /**
  69589. * Sets the current filter to Poisson Sampling.
  69590. */
  69591. set: function (value) {
  69592. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69593. return;
  69594. }
  69595. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69596. },
  69597. enumerable: true,
  69598. configurable: true
  69599. });
  69600. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69601. /**
  69602. * Gets if the current filter is set to VSM.
  69603. * DEPRECATED. Should use useExponentialShadowMap instead.
  69604. */
  69605. get: function () {
  69606. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69607. return this.useExponentialShadowMap;
  69608. },
  69609. /**
  69610. * Sets the current filter is to VSM.
  69611. * DEPRECATED. Should use useExponentialShadowMap instead.
  69612. */
  69613. set: function (value) {
  69614. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69615. this.useExponentialShadowMap = value;
  69616. },
  69617. enumerable: true,
  69618. configurable: true
  69619. });
  69620. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69621. /**
  69622. * Gets if the current filter is set to blurred VSM.
  69623. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69624. */
  69625. get: function () {
  69626. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69627. return this.useBlurExponentialShadowMap;
  69628. },
  69629. /**
  69630. * Sets the current filter is to blurred VSM.
  69631. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69632. */
  69633. set: function (value) {
  69634. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69635. this.useBlurExponentialShadowMap = value;
  69636. },
  69637. enumerable: true,
  69638. configurable: true
  69639. });
  69640. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69641. /**
  69642. * Gets if the current filter is set to ESM.
  69643. */
  69644. get: function () {
  69645. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69646. },
  69647. /**
  69648. * Sets the current filter is to ESM.
  69649. */
  69650. set: function (value) {
  69651. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69652. return;
  69653. }
  69654. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69655. },
  69656. enumerable: true,
  69657. configurable: true
  69658. });
  69659. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69660. /**
  69661. * Gets if the current filter is set to filtered ESM.
  69662. */
  69663. get: function () {
  69664. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69665. },
  69666. /**
  69667. * Gets if the current filter is set to filtered ESM.
  69668. */
  69669. set: function (value) {
  69670. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69671. return;
  69672. }
  69673. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69674. },
  69675. enumerable: true,
  69676. configurable: true
  69677. });
  69678. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69679. /**
  69680. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69681. * exponential to prevent steep falloff artifacts).
  69682. */
  69683. get: function () {
  69684. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69685. },
  69686. /**
  69687. * Sets the current filter to "close ESM" (using the inverse of the
  69688. * exponential to prevent steep falloff artifacts).
  69689. */
  69690. set: function (value) {
  69691. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69692. return;
  69693. }
  69694. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69695. },
  69696. enumerable: true,
  69697. configurable: true
  69698. });
  69699. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69700. /**
  69701. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69702. * exponential to prevent steep falloff artifacts).
  69703. */
  69704. get: function () {
  69705. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69706. },
  69707. /**
  69708. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69709. * exponential to prevent steep falloff artifacts).
  69710. */
  69711. set: function (value) {
  69712. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69713. return;
  69714. }
  69715. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69716. },
  69717. enumerable: true,
  69718. configurable: true
  69719. });
  69720. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69721. /**
  69722. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69723. */
  69724. get: function () {
  69725. return this.filter === ShadowGenerator.FILTER_PCF;
  69726. },
  69727. /**
  69728. * Sets the current filter to "PCF" (percentage closer filtering).
  69729. */
  69730. set: function (value) {
  69731. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69732. return;
  69733. }
  69734. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69735. },
  69736. enumerable: true,
  69737. configurable: true
  69738. });
  69739. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69740. /**
  69741. * Gets the PCF or PCSS Quality.
  69742. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69743. */
  69744. get: function () {
  69745. return this._filteringQuality;
  69746. },
  69747. /**
  69748. * Sets the PCF or PCSS Quality.
  69749. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69750. */
  69751. set: function (filteringQuality) {
  69752. this._filteringQuality = filteringQuality;
  69753. },
  69754. enumerable: true,
  69755. configurable: true
  69756. });
  69757. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69758. /**
  69759. * Gets if the current filter is set to "PCSS" (contact hardening).
  69760. */
  69761. get: function () {
  69762. return this.filter === ShadowGenerator.FILTER_PCSS;
  69763. },
  69764. /**
  69765. * Sets the current filter to "PCSS" (contact hardening).
  69766. */
  69767. set: function (value) {
  69768. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69769. return;
  69770. }
  69771. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69772. },
  69773. enumerable: true,
  69774. configurable: true
  69775. });
  69776. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69777. /**
  69778. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69779. * Using a ratio helps keeping shape stability independently of the map size.
  69780. *
  69781. * It does not account for the light projection as it was having too much
  69782. * instability during the light setup or during light position changes.
  69783. *
  69784. * Only valid if useContactHardeningShadow is true.
  69785. */
  69786. get: function () {
  69787. return this._contactHardeningLightSizeUVRatio;
  69788. },
  69789. /**
  69790. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69791. * Using a ratio helps keeping shape stability independently of the map size.
  69792. *
  69793. * It does not account for the light projection as it was having too much
  69794. * instability during the light setup or during light position changes.
  69795. *
  69796. * Only valid if useContactHardeningShadow is true.
  69797. */
  69798. set: function (contactHardeningLightSizeUVRatio) {
  69799. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69800. },
  69801. enumerable: true,
  69802. configurable: true
  69803. });
  69804. /**
  69805. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69806. * 0 means strongest and 1 would means no shadow.
  69807. * @returns the darkness.
  69808. */
  69809. ShadowGenerator.prototype.getDarkness = function () {
  69810. return this._darkness;
  69811. };
  69812. /**
  69813. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69814. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69815. * @returns the shadow generator allowing fluent coding.
  69816. */
  69817. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69818. if (darkness >= 1.0)
  69819. this._darkness = 1.0;
  69820. else if (darkness <= 0.0)
  69821. this._darkness = 0.0;
  69822. else
  69823. this._darkness = darkness;
  69824. return this;
  69825. };
  69826. /**
  69827. * Sets the ability to have transparent shadow (boolean).
  69828. * @param transparent True if transparent else False
  69829. * @returns the shadow generator allowing fluent coding
  69830. */
  69831. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69832. this._transparencyShadow = transparent;
  69833. return this;
  69834. };
  69835. /**
  69836. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69837. * @returns The render target texture if present otherwise, null
  69838. */
  69839. ShadowGenerator.prototype.getShadowMap = function () {
  69840. return this._shadowMap;
  69841. };
  69842. /**
  69843. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69844. * @returns The render target texture if the shadow map is present otherwise, null
  69845. */
  69846. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69847. if (this._shadowMap2) {
  69848. return this._shadowMap2;
  69849. }
  69850. return this._shadowMap;
  69851. };
  69852. /**
  69853. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69854. * @param mesh Mesh to add
  69855. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69856. * @returns the Shadow Generator itself
  69857. */
  69858. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69859. if (includeDescendants === void 0) { includeDescendants = true; }
  69860. var _a;
  69861. if (!this._shadowMap) {
  69862. return this;
  69863. }
  69864. if (!this._shadowMap.renderList) {
  69865. this._shadowMap.renderList = [];
  69866. }
  69867. this._shadowMap.renderList.push(mesh);
  69868. if (includeDescendants) {
  69869. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69870. }
  69871. return this;
  69872. };
  69873. /**
  69874. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69875. * @param mesh Mesh to remove
  69876. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69877. * @returns the Shadow Generator itself
  69878. */
  69879. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69880. if (includeDescendants === void 0) { includeDescendants = true; }
  69881. if (!this._shadowMap || !this._shadowMap.renderList) {
  69882. return this;
  69883. }
  69884. var index = this._shadowMap.renderList.indexOf(mesh);
  69885. if (index !== -1) {
  69886. this._shadowMap.renderList.splice(index, 1);
  69887. }
  69888. if (includeDescendants) {
  69889. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69890. var child = _a[_i];
  69891. this.removeShadowCaster(child);
  69892. }
  69893. }
  69894. return this;
  69895. };
  69896. /**
  69897. * Returns the associated light object.
  69898. * @returns the light generating the shadow
  69899. */
  69900. ShadowGenerator.prototype.getLight = function () {
  69901. return this._light;
  69902. };
  69903. ShadowGenerator.prototype._initializeGenerator = function () {
  69904. this._light._markMeshesAsLightDirty();
  69905. this._initializeShadowMap();
  69906. };
  69907. ShadowGenerator.prototype._initializeShadowMap = function () {
  69908. var _this = this;
  69909. // Render target
  69910. var engine = this._scene.getEngine();
  69911. if (engine.webGLVersion > 1) {
  69912. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69913. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69914. }
  69915. else {
  69916. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69917. }
  69918. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69919. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69920. this._shadowMap.anisotropicFilteringLevel = 1;
  69921. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69922. this._shadowMap.renderParticles = false;
  69923. this._shadowMap.ignoreCameraViewport = true;
  69924. // Record Face Index before render.
  69925. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69926. _this._currentFaceIndex = faceIndex;
  69927. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69928. engine.setColorWrite(false);
  69929. }
  69930. });
  69931. // Custom render function.
  69932. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69933. // Blur if required afer render.
  69934. this._shadowMap.onAfterUnbindObservable.add(function () {
  69935. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69936. engine.setColorWrite(true);
  69937. }
  69938. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69939. return;
  69940. }
  69941. var shadowMap = _this.getShadowMapForRendering();
  69942. if (shadowMap) {
  69943. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69944. }
  69945. });
  69946. // Clear according to the chosen filter.
  69947. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69948. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69949. this._shadowMap.onClearObservable.add(function (engine) {
  69950. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69951. engine.clear(clearOne, false, true, false);
  69952. }
  69953. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69954. engine.clear(clearZero, true, true, false);
  69955. }
  69956. else {
  69957. engine.clear(clearOne, true, true, false);
  69958. }
  69959. });
  69960. };
  69961. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69962. var _this = this;
  69963. var engine = this._scene.getEngine();
  69964. var targetSize = this._mapSize / this.blurScale;
  69965. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69966. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69967. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69968. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69969. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69970. }
  69971. if (this.useKernelBlur) {
  69972. 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);
  69973. this._kernelBlurXPostprocess.width = targetSize;
  69974. this._kernelBlurXPostprocess.height = targetSize;
  69975. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69976. effect.setTexture("textureSampler", _this._shadowMap);
  69977. });
  69978. 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);
  69979. this._kernelBlurXPostprocess.autoClear = false;
  69980. this._kernelBlurYPostprocess.autoClear = false;
  69981. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69982. this._kernelBlurXPostprocess.packedFloat = true;
  69983. this._kernelBlurYPostprocess.packedFloat = true;
  69984. }
  69985. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69986. }
  69987. else {
  69988. 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);
  69989. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69990. effect.setFloat2("screenSize", targetSize, targetSize);
  69991. effect.setTexture("textureSampler", _this._shadowMap);
  69992. });
  69993. this._boxBlurPostprocess.autoClear = false;
  69994. this._blurPostProcesses = [this._boxBlurPostprocess];
  69995. }
  69996. };
  69997. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69998. var index;
  69999. var engine = this._scene.getEngine();
  70000. if (depthOnlySubMeshes.length) {
  70001. engine.setColorWrite(false);
  70002. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70003. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70004. }
  70005. engine.setColorWrite(true);
  70006. }
  70007. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70008. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70009. }
  70010. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70011. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70012. }
  70013. if (this._transparencyShadow) {
  70014. for (index = 0; index < transparentSubMeshes.length; index++) {
  70015. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70016. }
  70017. }
  70018. };
  70019. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70020. var _this = this;
  70021. var mesh = subMesh.getRenderingMesh();
  70022. var scene = this._scene;
  70023. var engine = scene.getEngine();
  70024. var material = subMesh.getMaterial();
  70025. if (!material) {
  70026. return;
  70027. }
  70028. // Culling
  70029. engine.setState(material.backFaceCulling);
  70030. // Managing instances
  70031. var batch = mesh._getInstancesRenderList(subMesh._id);
  70032. if (batch.mustReturn) {
  70033. return;
  70034. }
  70035. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70036. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70037. engine.enableEffect(this._effect);
  70038. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70039. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70040. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70041. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70042. this._effect.setVector3("lightData", this._cachedDirection);
  70043. }
  70044. else {
  70045. this._effect.setVector3("lightData", this._cachedPosition);
  70046. }
  70047. if (scene.activeCamera) {
  70048. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70049. }
  70050. // Alpha test
  70051. if (material && material.needAlphaTesting()) {
  70052. var alphaTexture = material.getAlphaTestTexture();
  70053. if (alphaTexture) {
  70054. this._effect.setTexture("diffuseSampler", alphaTexture);
  70055. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70056. }
  70057. }
  70058. // Bones
  70059. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70060. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70061. }
  70062. // Morph targets
  70063. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70064. if (this.forceBackFacesOnly) {
  70065. engine.setState(true, 0, false, true);
  70066. }
  70067. // Draw
  70068. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70069. if (this.forceBackFacesOnly) {
  70070. engine.setState(true, 0, false, false);
  70071. }
  70072. }
  70073. else {
  70074. // Need to reset refresh rate of the shadowMap
  70075. if (this._shadowMap) {
  70076. this._shadowMap.resetRefreshCounter();
  70077. }
  70078. }
  70079. };
  70080. ShadowGenerator.prototype._applyFilterValues = function () {
  70081. if (!this._shadowMap) {
  70082. return;
  70083. }
  70084. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70085. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70086. }
  70087. else {
  70088. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70089. }
  70090. };
  70091. /**
  70092. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70093. * @param onCompiled Callback triggered at the and of the effects compilation
  70094. * @param options Sets of optional options forcing the compilation with different modes
  70095. */
  70096. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70097. var _this = this;
  70098. var localOptions = __assign({ useInstances: false }, options);
  70099. var shadowMap = this.getShadowMap();
  70100. if (!shadowMap) {
  70101. if (onCompiled) {
  70102. onCompiled(this);
  70103. }
  70104. return;
  70105. }
  70106. var renderList = shadowMap.renderList;
  70107. if (!renderList) {
  70108. if (onCompiled) {
  70109. onCompiled(this);
  70110. }
  70111. return;
  70112. }
  70113. var subMeshes = new Array();
  70114. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70115. var mesh = renderList_1[_i];
  70116. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70117. }
  70118. if (subMeshes.length === 0) {
  70119. if (onCompiled) {
  70120. onCompiled(this);
  70121. }
  70122. return;
  70123. }
  70124. var currentIndex = 0;
  70125. var checkReady = function () {
  70126. if (!_this._scene || !_this._scene.getEngine()) {
  70127. return;
  70128. }
  70129. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70130. currentIndex++;
  70131. if (currentIndex >= subMeshes.length) {
  70132. if (onCompiled) {
  70133. onCompiled(_this);
  70134. }
  70135. return;
  70136. }
  70137. }
  70138. setTimeout(checkReady, 16);
  70139. };
  70140. checkReady();
  70141. };
  70142. /**
  70143. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70144. * @param options Sets of optional options forcing the compilation with different modes
  70145. * @returns A promise that resolves when the compilation completes
  70146. */
  70147. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70148. var _this = this;
  70149. return new Promise(function (resolve) {
  70150. _this.forceCompilation(function () {
  70151. resolve();
  70152. }, options);
  70153. });
  70154. };
  70155. /**
  70156. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70157. * @param subMesh The submesh we want to render in the shadow map
  70158. * @param useInstances Defines wether will draw in the map using instances
  70159. * @returns true if ready otherwise, false
  70160. */
  70161. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70162. var defines = [];
  70163. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70164. defines.push("#define FLOAT");
  70165. }
  70166. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70167. defines.push("#define ESM");
  70168. }
  70169. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70170. defines.push("#define DEPTHTEXTURE");
  70171. }
  70172. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70173. var mesh = subMesh.getMesh();
  70174. var material = subMesh.getMaterial();
  70175. // Normal bias.
  70176. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70177. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70178. defines.push("#define NORMAL");
  70179. if (mesh.nonUniformScaling) {
  70180. defines.push("#define NONUNIFORMSCALING");
  70181. }
  70182. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70183. defines.push("#define DIRECTIONINLIGHTDATA");
  70184. }
  70185. }
  70186. // Alpha test
  70187. if (material && material.needAlphaTesting()) {
  70188. var alphaTexture = material.getAlphaTestTexture();
  70189. if (alphaTexture) {
  70190. defines.push("#define ALPHATEST");
  70191. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70192. attribs.push(BABYLON.VertexBuffer.UVKind);
  70193. defines.push("#define UV1");
  70194. }
  70195. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70196. if (alphaTexture.coordinatesIndex === 1) {
  70197. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70198. defines.push("#define UV2");
  70199. }
  70200. }
  70201. }
  70202. }
  70203. // Bones
  70204. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70207. if (mesh.numBoneInfluencers > 4) {
  70208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70210. }
  70211. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70212. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70213. }
  70214. else {
  70215. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70216. }
  70217. // Morph targets
  70218. var manager = mesh.morphTargetManager;
  70219. var morphInfluencers = 0;
  70220. if (manager) {
  70221. if (manager.numInfluencers > 0) {
  70222. defines.push("#define MORPHTARGETS");
  70223. morphInfluencers = manager.numInfluencers;
  70224. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70225. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70226. }
  70227. }
  70228. // Instances
  70229. if (useInstances) {
  70230. defines.push("#define INSTANCES");
  70231. attribs.push("world0");
  70232. attribs.push("world1");
  70233. attribs.push("world2");
  70234. attribs.push("world3");
  70235. }
  70236. // Get correct effect
  70237. var join = defines.join("\n");
  70238. if (this._cachedDefines !== join) {
  70239. this._cachedDefines = join;
  70240. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  70241. }
  70242. if (!this._effect.isReady()) {
  70243. return false;
  70244. }
  70245. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70246. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  70247. this._initializeBlurRTTAndPostProcesses();
  70248. }
  70249. }
  70250. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  70251. return false;
  70252. }
  70253. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  70254. return false;
  70255. }
  70256. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  70257. return false;
  70258. }
  70259. return true;
  70260. };
  70261. /**
  70262. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  70263. * @param defines Defines of the material we want to update
  70264. * @param lightIndex Index of the light in the enabled light list of the material
  70265. */
  70266. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  70267. var scene = this._scene;
  70268. var light = this._light;
  70269. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70270. return;
  70271. }
  70272. defines["SHADOW" + lightIndex] = true;
  70273. if (this.useContactHardeningShadow) {
  70274. defines["SHADOWPCSS" + lightIndex] = true;
  70275. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70276. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70277. }
  70278. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70279. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70280. }
  70281. // else default to high.
  70282. }
  70283. if (this.usePercentageCloserFiltering) {
  70284. defines["SHADOWPCF" + lightIndex] = true;
  70285. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70286. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70287. }
  70288. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70289. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70290. }
  70291. // else default to high.
  70292. }
  70293. else if (this.usePoissonSampling) {
  70294. defines["SHADOWPOISSON" + lightIndex] = true;
  70295. }
  70296. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70297. defines["SHADOWESM" + lightIndex] = true;
  70298. }
  70299. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70300. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70301. }
  70302. if (light.needCube()) {
  70303. defines["SHADOWCUBE" + lightIndex] = true;
  70304. }
  70305. };
  70306. /**
  70307. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70308. * defined in the generator but impacting the effect).
  70309. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70310. * @param effect The effect we are binfing the information for
  70311. */
  70312. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70313. var light = this._light;
  70314. var scene = this._scene;
  70315. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70316. return;
  70317. }
  70318. var camera = scene.activeCamera;
  70319. if (!camera) {
  70320. return;
  70321. }
  70322. var shadowMap = this.getShadowMap();
  70323. if (!shadowMap) {
  70324. return;
  70325. }
  70326. if (!light.needCube()) {
  70327. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70328. }
  70329. // Only PCF uses depth stencil texture.
  70330. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70331. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70332. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70333. }
  70334. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70335. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70336. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70337. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70338. }
  70339. else {
  70340. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70341. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70342. }
  70343. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70344. };
  70345. /**
  70346. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70347. * (eq to shadow prjection matrix * light transform matrix)
  70348. * @returns The transform matrix used to create the shadow map
  70349. */
  70350. ShadowGenerator.prototype.getTransformMatrix = function () {
  70351. var scene = this._scene;
  70352. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70353. return this._transformMatrix;
  70354. }
  70355. this._currentRenderID = scene.getRenderId();
  70356. this._currentFaceIndexCache = this._currentFaceIndex;
  70357. var lightPosition = this._light.position;
  70358. if (this._light.computeTransformedInformation()) {
  70359. lightPosition = this._light.transformedPosition;
  70360. }
  70361. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70362. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70363. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70364. }
  70365. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70366. this._cachedPosition.copyFrom(lightPosition);
  70367. this._cachedDirection.copyFrom(this._lightDirection);
  70368. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70369. var shadowMap = this.getShadowMap();
  70370. if (shadowMap) {
  70371. var renderList = shadowMap.renderList;
  70372. if (renderList) {
  70373. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70374. }
  70375. }
  70376. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70377. }
  70378. return this._transformMatrix;
  70379. };
  70380. /**
  70381. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70382. * Cube and 2D textures for instance.
  70383. */
  70384. ShadowGenerator.prototype.recreateShadowMap = function () {
  70385. var shadowMap = this._shadowMap;
  70386. if (!shadowMap) {
  70387. return;
  70388. }
  70389. // Track render list.
  70390. var renderList = shadowMap.renderList;
  70391. // Clean up existing data.
  70392. this._disposeRTTandPostProcesses();
  70393. // Reinitializes.
  70394. this._initializeGenerator();
  70395. // Reaffect the filter to ensure a correct fallback if necessary.
  70396. this.filter = this.filter;
  70397. // Reaffect the filter.
  70398. this._applyFilterValues();
  70399. // Reaffect Render List.
  70400. this._shadowMap.renderList = renderList;
  70401. };
  70402. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70403. if (this._shadowMap2) {
  70404. this._shadowMap2.dispose();
  70405. this._shadowMap2 = null;
  70406. }
  70407. if (this._boxBlurPostprocess) {
  70408. this._boxBlurPostprocess.dispose();
  70409. this._boxBlurPostprocess = null;
  70410. }
  70411. if (this._kernelBlurXPostprocess) {
  70412. this._kernelBlurXPostprocess.dispose();
  70413. this._kernelBlurXPostprocess = null;
  70414. }
  70415. if (this._kernelBlurYPostprocess) {
  70416. this._kernelBlurYPostprocess.dispose();
  70417. this._kernelBlurYPostprocess = null;
  70418. }
  70419. this._blurPostProcesses = [];
  70420. };
  70421. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70422. if (this._shadowMap) {
  70423. this._shadowMap.dispose();
  70424. this._shadowMap = null;
  70425. }
  70426. this._disposeBlurPostProcesses();
  70427. };
  70428. /**
  70429. * Disposes the ShadowGenerator.
  70430. * Returns nothing.
  70431. */
  70432. ShadowGenerator.prototype.dispose = function () {
  70433. this._disposeRTTandPostProcesses();
  70434. if (this._light) {
  70435. this._light._shadowGenerator = null;
  70436. this._light._markMeshesAsLightDirty();
  70437. }
  70438. };
  70439. /**
  70440. * Serializes the shadow generator setup to a json object.
  70441. * @returns The serialized JSON object
  70442. */
  70443. ShadowGenerator.prototype.serialize = function () {
  70444. var serializationObject = {};
  70445. var shadowMap = this.getShadowMap();
  70446. if (!shadowMap) {
  70447. return serializationObject;
  70448. }
  70449. serializationObject.lightId = this._light.id;
  70450. serializationObject.mapSize = shadowMap.getRenderSize();
  70451. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70452. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70453. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70454. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70455. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70456. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70457. serializationObject.depthScale = this.depthScale;
  70458. serializationObject.darkness = this.getDarkness();
  70459. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70460. serializationObject.blurKernel = this.blurKernel;
  70461. serializationObject.blurScale = this.blurScale;
  70462. serializationObject.useKernelBlur = this.useKernelBlur;
  70463. serializationObject.transparencyShadow = this._transparencyShadow;
  70464. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70465. serializationObject.bias = this.bias;
  70466. serializationObject.normalBias = this.normalBias;
  70467. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70468. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70469. serializationObject.filteringQuality = this.filteringQuality;
  70470. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70471. serializationObject.renderList = [];
  70472. if (shadowMap.renderList) {
  70473. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70474. var mesh = shadowMap.renderList[meshIndex];
  70475. serializationObject.renderList.push(mesh.id);
  70476. }
  70477. }
  70478. return serializationObject;
  70479. };
  70480. /**
  70481. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70482. * @param parsedShadowGenerator The JSON object to parse
  70483. * @param scene The scene to create the shadow map for
  70484. * @returns The parsed shadow generator
  70485. */
  70486. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70487. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70488. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70489. var shadowMap = shadowGenerator.getShadowMap();
  70490. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70491. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70492. meshes.forEach(function (mesh) {
  70493. if (!shadowMap) {
  70494. return;
  70495. }
  70496. if (!shadowMap.renderList) {
  70497. shadowMap.renderList = [];
  70498. }
  70499. shadowMap.renderList.push(mesh);
  70500. });
  70501. }
  70502. if (parsedShadowGenerator.usePoissonSampling) {
  70503. shadowGenerator.usePoissonSampling = true;
  70504. }
  70505. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70506. shadowGenerator.useExponentialShadowMap = true;
  70507. }
  70508. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70509. shadowGenerator.useBlurExponentialShadowMap = true;
  70510. }
  70511. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70512. shadowGenerator.useCloseExponentialShadowMap = true;
  70513. }
  70514. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70515. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70516. }
  70517. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70518. shadowGenerator.usePercentageCloserFiltering = true;
  70519. }
  70520. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70521. shadowGenerator.useContactHardeningShadow = true;
  70522. }
  70523. if (parsedShadowGenerator.filteringQuality) {
  70524. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70525. }
  70526. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70527. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70528. }
  70529. // Backward compat
  70530. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70531. shadowGenerator.useExponentialShadowMap = true;
  70532. }
  70533. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70534. shadowGenerator.useBlurExponentialShadowMap = true;
  70535. }
  70536. if (parsedShadowGenerator.depthScale) {
  70537. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70538. }
  70539. if (parsedShadowGenerator.blurScale) {
  70540. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70541. }
  70542. if (parsedShadowGenerator.blurBoxOffset) {
  70543. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70544. }
  70545. if (parsedShadowGenerator.useKernelBlur) {
  70546. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70547. }
  70548. if (parsedShadowGenerator.blurKernel) {
  70549. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70550. }
  70551. if (parsedShadowGenerator.bias !== undefined) {
  70552. shadowGenerator.bias = parsedShadowGenerator.bias;
  70553. }
  70554. if (parsedShadowGenerator.normalBias !== undefined) {
  70555. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70556. }
  70557. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70558. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70559. }
  70560. if (parsedShadowGenerator.darkness) {
  70561. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70562. }
  70563. if (parsedShadowGenerator.transparencyShadow) {
  70564. shadowGenerator.setTransparencyShadow(true);
  70565. }
  70566. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70567. return shadowGenerator;
  70568. };
  70569. /**
  70570. * Shadow generator mode None: no filtering applied.
  70571. */
  70572. ShadowGenerator.FILTER_NONE = 0;
  70573. /**
  70574. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70575. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70576. */
  70577. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70578. /**
  70579. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70580. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70581. */
  70582. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70583. /**
  70584. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70585. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70586. */
  70587. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70588. /**
  70589. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70590. * edge artifacts on steep falloff.
  70591. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70592. */
  70593. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70594. /**
  70595. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70596. * edge artifacts on steep falloff.
  70597. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70598. */
  70599. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70600. /**
  70601. * Shadow generator mode PCF: Percentage Closer Filtering
  70602. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70603. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70604. */
  70605. ShadowGenerator.FILTER_PCF = 6;
  70606. /**
  70607. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70608. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70609. * Contact Hardening
  70610. */
  70611. ShadowGenerator.FILTER_PCSS = 7;
  70612. /**
  70613. * Reserved for PCF and PCSS
  70614. * Highest Quality.
  70615. *
  70616. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70617. *
  70618. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70619. */
  70620. ShadowGenerator.QUALITY_HIGH = 0;
  70621. /**
  70622. * Reserved for PCF and PCSS
  70623. * Good tradeoff for quality/perf cross devices
  70624. *
  70625. * Execute PCF on a 3*3 kernel.
  70626. *
  70627. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70628. */
  70629. ShadowGenerator.QUALITY_MEDIUM = 1;
  70630. /**
  70631. * Reserved for PCF and PCSS
  70632. * The lowest quality but the fastest.
  70633. *
  70634. * Execute PCF on a 1*1 kernel.
  70635. *
  70636. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70637. */
  70638. ShadowGenerator.QUALITY_LOW = 2;
  70639. return ShadowGenerator;
  70640. }());
  70641. BABYLON.ShadowGenerator = ShadowGenerator;
  70642. })(BABYLON || (BABYLON = {}));
  70643. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70644. var BABYLON;
  70645. (function (BABYLON) {
  70646. // Adds the parser to the scene parsers.
  70647. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  70648. // Shadows
  70649. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70650. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70651. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70652. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70653. // SG would be available on their associated lights
  70654. }
  70655. }
  70656. });
  70657. /**
  70658. * Defines the shadow generator component responsible to manage any shadow generators
  70659. * in a given scene.
  70660. */
  70661. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  70662. /**
  70663. * Creates a new instance of the component for the given scene
  70664. * @param scene Defines the scene to register the component in
  70665. */
  70666. function ShadowGeneratorSceneComponent(scene) {
  70667. /**
  70668. * The component name helpfull to identify the component in the list of scene components.
  70669. */
  70670. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  70671. this.scene = scene;
  70672. }
  70673. /**
  70674. * Registers the component in a given scene
  70675. */
  70676. ShadowGeneratorSceneComponent.prototype.register = function () {
  70677. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  70678. };
  70679. /**
  70680. * Rebuilds the elements related to this component in case of
  70681. * context lost for instance.
  70682. */
  70683. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  70684. // Nothing To Do Here.
  70685. };
  70686. /**
  70687. * Serializes the component data to the specified json object
  70688. * @param serializationObject The object to serialize to
  70689. */
  70690. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  70691. // Shadows
  70692. serializationObject.shadowGenerators = [];
  70693. var lights = this.scene.lights;
  70694. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  70695. var light = lights_1[_i];
  70696. var shadowGenerator = light.getShadowGenerator();
  70697. if (shadowGenerator) {
  70698. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70699. }
  70700. }
  70701. };
  70702. /**
  70703. * Adds all the element from the container to the scene
  70704. * @param container the container holding the elements
  70705. */
  70706. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  70707. // Nothing To Do Here. (directly attached to a light)
  70708. };
  70709. /**
  70710. * Removes all the elements in the container from the scene
  70711. * @param container contains the elements to remove
  70712. */
  70713. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  70714. // Nothing To Do Here. (directly attached to a light)
  70715. };
  70716. /**
  70717. * Rebuilds the elements related to this component in case of
  70718. * context lost for instance.
  70719. */
  70720. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  70721. // Nothing To Do Here.
  70722. };
  70723. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  70724. // Shadows
  70725. var scene = this.scene;
  70726. if (this.scene.shadowsEnabled) {
  70727. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  70728. var light = scene.lights[lightIndex];
  70729. var shadowGenerator = light.getShadowGenerator();
  70730. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  70731. var shadowMap = (shadowGenerator.getShadowMap());
  70732. if (scene.textures.indexOf(shadowMap) !== -1) {
  70733. renderTargets.push(shadowMap);
  70734. }
  70735. }
  70736. }
  70737. }
  70738. };
  70739. return ShadowGeneratorSceneComponent;
  70740. }());
  70741. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  70742. })(BABYLON || (BABYLON = {}));
  70743. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  70744. var BABYLON;
  70745. (function (BABYLON) {
  70746. var DefaultLoadingScreen = /** @class */ (function () {
  70747. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70748. if (_loadingText === void 0) { _loadingText = ""; }
  70749. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70750. var _this = this;
  70751. this._renderingCanvas = _renderingCanvas;
  70752. this._loadingText = _loadingText;
  70753. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70754. // Resize
  70755. this._resizeLoadingUI = function () {
  70756. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70757. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70758. if (!_this._loadingDiv) {
  70759. return;
  70760. }
  70761. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70762. _this._loadingDiv.style.left = canvasRect.left + "px";
  70763. _this._loadingDiv.style.top = canvasRect.top + "px";
  70764. _this._loadingDiv.style.width = canvasRect.width + "px";
  70765. _this._loadingDiv.style.height = canvasRect.height + "px";
  70766. };
  70767. }
  70768. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70769. if (this._loadingDiv) {
  70770. // Do not add a loading screen if there is already one
  70771. return;
  70772. }
  70773. this._loadingDiv = document.createElement("div");
  70774. this._loadingDiv.id = "babylonjsLoadingDiv";
  70775. this._loadingDiv.style.opacity = "0";
  70776. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70777. this._loadingDiv.style.pointerEvents = "none";
  70778. // Loading text
  70779. this._loadingTextDiv = document.createElement("div");
  70780. this._loadingTextDiv.style.position = "absolute";
  70781. this._loadingTextDiv.style.left = "0";
  70782. this._loadingTextDiv.style.top = "50%";
  70783. this._loadingTextDiv.style.marginTop = "80px";
  70784. this._loadingTextDiv.style.width = "100%";
  70785. this._loadingTextDiv.style.height = "20px";
  70786. this._loadingTextDiv.style.fontFamily = "Arial";
  70787. this._loadingTextDiv.style.fontSize = "14px";
  70788. this._loadingTextDiv.style.color = "white";
  70789. this._loadingTextDiv.style.textAlign = "center";
  70790. this._loadingTextDiv.innerHTML = "Loading";
  70791. this._loadingDiv.appendChild(this._loadingTextDiv);
  70792. //set the predefined text
  70793. this._loadingTextDiv.innerHTML = this._loadingText;
  70794. // Generating keyframes
  70795. var style = document.createElement('style');
  70796. style.type = 'text/css';
  70797. 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 }";
  70798. style.innerHTML = keyFrames;
  70799. document.getElementsByTagName('head')[0].appendChild(style);
  70800. // Loading img
  70801. var imgBack = new Image();
  70802. 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";
  70803. imgBack.style.position = "absolute";
  70804. imgBack.style.left = "50%";
  70805. imgBack.style.top = "50%";
  70806. imgBack.style.marginLeft = "-60px";
  70807. imgBack.style.marginTop = "-60px";
  70808. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70809. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70810. imgBack.style.transformOrigin = "50% 50%";
  70811. imgBack.style.webkitTransformOrigin = "50% 50%";
  70812. this._loadingDiv.appendChild(imgBack);
  70813. this._resizeLoadingUI();
  70814. window.addEventListener("resize", this._resizeLoadingUI);
  70815. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70816. document.body.appendChild(this._loadingDiv);
  70817. this._loadingDiv.style.opacity = "1";
  70818. };
  70819. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70820. var _this = this;
  70821. if (!this._loadingDiv) {
  70822. return;
  70823. }
  70824. var onTransitionEnd = function () {
  70825. if (!_this._loadingDiv) {
  70826. return;
  70827. }
  70828. document.body.removeChild(_this._loadingDiv);
  70829. window.removeEventListener("resize", _this._resizeLoadingUI);
  70830. _this._loadingDiv = null;
  70831. };
  70832. this._loadingDiv.style.opacity = "0";
  70833. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70834. };
  70835. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70836. set: function (text) {
  70837. this._loadingText = text;
  70838. if (this._loadingTextDiv) {
  70839. this._loadingTextDiv.innerHTML = this._loadingText;
  70840. }
  70841. },
  70842. enumerable: true,
  70843. configurable: true
  70844. });
  70845. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70846. get: function () {
  70847. return this._loadingDivBackgroundColor;
  70848. },
  70849. set: function (color) {
  70850. this._loadingDivBackgroundColor = color;
  70851. if (!this._loadingDiv) {
  70852. return;
  70853. }
  70854. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70855. },
  70856. enumerable: true,
  70857. configurable: true
  70858. });
  70859. return DefaultLoadingScreen;
  70860. }());
  70861. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70862. })(BABYLON || (BABYLON = {}));
  70863. //# sourceMappingURL=babylon.loadingScreen.js.map
  70864. var BABYLON;
  70865. (function (BABYLON) {
  70866. var SceneLoaderProgressEvent = /** @class */ (function () {
  70867. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70868. this.lengthComputable = lengthComputable;
  70869. this.loaded = loaded;
  70870. this.total = total;
  70871. }
  70872. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70873. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70874. };
  70875. return SceneLoaderProgressEvent;
  70876. }());
  70877. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70878. var SceneLoader = /** @class */ (function () {
  70879. function SceneLoader() {
  70880. }
  70881. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70882. get: function () {
  70883. return 0;
  70884. },
  70885. enumerable: true,
  70886. configurable: true
  70887. });
  70888. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70889. get: function () {
  70890. return 1;
  70891. },
  70892. enumerable: true,
  70893. configurable: true
  70894. });
  70895. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70896. get: function () {
  70897. return 2;
  70898. },
  70899. enumerable: true,
  70900. configurable: true
  70901. });
  70902. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70903. get: function () {
  70904. return 3;
  70905. },
  70906. enumerable: true,
  70907. configurable: true
  70908. });
  70909. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70910. get: function () {
  70911. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70912. },
  70913. set: function (value) {
  70914. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70915. },
  70916. enumerable: true,
  70917. configurable: true
  70918. });
  70919. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70920. get: function () {
  70921. return SceneLoader._ShowLoadingScreen;
  70922. },
  70923. set: function (value) {
  70924. SceneLoader._ShowLoadingScreen = value;
  70925. },
  70926. enumerable: true,
  70927. configurable: true
  70928. });
  70929. Object.defineProperty(SceneLoader, "loggingLevel", {
  70930. get: function () {
  70931. return SceneLoader._loggingLevel;
  70932. },
  70933. set: function (value) {
  70934. SceneLoader._loggingLevel = value;
  70935. },
  70936. enumerable: true,
  70937. configurable: true
  70938. });
  70939. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70940. get: function () {
  70941. return SceneLoader._CleanBoneMatrixWeights;
  70942. },
  70943. set: function (value) {
  70944. SceneLoader._CleanBoneMatrixWeights = value;
  70945. },
  70946. enumerable: true,
  70947. configurable: true
  70948. });
  70949. SceneLoader._getDefaultPlugin = function () {
  70950. return SceneLoader._registeredPlugins[".babylon"];
  70951. };
  70952. SceneLoader._getPluginForExtension = function (extension) {
  70953. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70954. if (registeredPlugin) {
  70955. return registeredPlugin;
  70956. }
  70957. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  70958. return SceneLoader._getDefaultPlugin();
  70959. };
  70960. SceneLoader._getPluginForDirectLoad = function (data) {
  70961. for (var extension in SceneLoader._registeredPlugins) {
  70962. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70963. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70964. return SceneLoader._registeredPlugins[extension];
  70965. }
  70966. }
  70967. return SceneLoader._getDefaultPlugin();
  70968. };
  70969. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70970. if (sceneFilename.name) {
  70971. sceneFilename = sceneFilename.name;
  70972. }
  70973. var queryStringPosition = sceneFilename.indexOf("?");
  70974. if (queryStringPosition !== -1) {
  70975. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70976. }
  70977. var dotPosition = sceneFilename.lastIndexOf(".");
  70978. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70979. return SceneLoader._getPluginForExtension(extension);
  70980. };
  70981. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70982. SceneLoader._getDirectLoad = function (sceneFilename) {
  70983. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70984. return sceneFilename.substr(5);
  70985. }
  70986. return null;
  70987. };
  70988. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70989. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70990. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70991. var plugin;
  70992. if (registeredPlugin.plugin.createPlugin) {
  70993. plugin = registeredPlugin.plugin.createPlugin();
  70994. }
  70995. else {
  70996. plugin = registeredPlugin.plugin;
  70997. }
  70998. var useArrayBuffer = registeredPlugin.isBinary;
  70999. var database;
  71000. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71001. var dataCallback = function (data, responseURL) {
  71002. if (scene.isDisposed) {
  71003. onError("Scene has been disposed");
  71004. return;
  71005. }
  71006. scene.database = database;
  71007. onSuccess(plugin, data, responseURL);
  71008. };
  71009. var request = null;
  71010. var pluginDisposed = false;
  71011. var onDisposeObservable = plugin.onDisposeObservable;
  71012. if (onDisposeObservable) {
  71013. onDisposeObservable.add(function () {
  71014. pluginDisposed = true;
  71015. if (request) {
  71016. request.abort();
  71017. request = null;
  71018. }
  71019. onDispose();
  71020. });
  71021. }
  71022. var manifestChecked = function () {
  71023. if (pluginDisposed) {
  71024. return;
  71025. }
  71026. var url = rootUrl + sceneFilename;
  71027. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  71028. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71029. } : undefined, database, useArrayBuffer, function (request, exception) {
  71030. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71031. });
  71032. };
  71033. if (directLoad) {
  71034. dataCallback(directLoad);
  71035. return plugin;
  71036. }
  71037. if (rootUrl.indexOf("file:") === -1) {
  71038. var engine = scene.getEngine();
  71039. var canUseOfflineSupport = engine.enableOfflineSupport;
  71040. if (canUseOfflineSupport) {
  71041. // Also check for exceptions
  71042. var exceptionFound = false;
  71043. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71044. var regex = _a[_i];
  71045. if (regex.test(rootUrl + sceneFilename)) {
  71046. exceptionFound = true;
  71047. break;
  71048. }
  71049. }
  71050. canUseOfflineSupport = !exceptionFound;
  71051. }
  71052. if (canUseOfflineSupport) {
  71053. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71054. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  71055. }
  71056. else {
  71057. manifestChecked();
  71058. }
  71059. }
  71060. // Loading file from disk via input file or drag'n'drop
  71061. else {
  71062. var fileOrString = sceneFilename;
  71063. if (fileOrString.name) { // File
  71064. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  71065. }
  71066. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  71067. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  71068. }
  71069. else {
  71070. onError("Unable to find file named " + sceneFilename);
  71071. }
  71072. }
  71073. return plugin;
  71074. };
  71075. // Public functions
  71076. SceneLoader.GetPluginForExtension = function (extension) {
  71077. return SceneLoader._getPluginForExtension(extension).plugin;
  71078. };
  71079. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71080. return !!SceneLoader._registeredPlugins[extension];
  71081. };
  71082. SceneLoader.RegisterPlugin = function (plugin) {
  71083. if (typeof plugin.extensions === "string") {
  71084. var extension = plugin.extensions;
  71085. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71086. plugin: plugin,
  71087. isBinary: false
  71088. };
  71089. }
  71090. else {
  71091. var extensions = plugin.extensions;
  71092. Object.keys(extensions).forEach(function (extension) {
  71093. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71094. plugin: plugin,
  71095. isBinary: extensions[extension].isBinary
  71096. };
  71097. });
  71098. }
  71099. };
  71100. /**
  71101. * Import meshes into a scene
  71102. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71103. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71104. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71105. * @param scene the instance of BABYLON.Scene to append to
  71106. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71107. * @param onProgress a callback with a progress event for each file being loaded
  71108. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71109. * @param pluginExtension the extension used to determine the plugin
  71110. * @returns The loaded plugin
  71111. */
  71112. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71113. if (sceneFilename === void 0) { sceneFilename = ""; }
  71114. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71115. if (onSuccess === void 0) { onSuccess = null; }
  71116. if (onProgress === void 0) { onProgress = null; }
  71117. if (onError === void 0) { onError = null; }
  71118. if (pluginExtension === void 0) { pluginExtension = null; }
  71119. if (!scene) {
  71120. BABYLON.Tools.Error("No scene available to import mesh to");
  71121. return null;
  71122. }
  71123. if (!sceneFilename) {
  71124. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71125. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71126. }
  71127. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71128. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71129. return null;
  71130. }
  71131. var loadingToken = {};
  71132. scene._addPendingData(loadingToken);
  71133. var disposeHandler = function () {
  71134. scene._removePendingData(loadingToken);
  71135. };
  71136. var errorHandler = function (message, exception) {
  71137. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  71138. if (onError) {
  71139. onError(scene, errorMessage, exception);
  71140. }
  71141. else {
  71142. BABYLON.Tools.Error(errorMessage);
  71143. // should the exception be thrown?
  71144. }
  71145. disposeHandler();
  71146. };
  71147. var progressHandler = onProgress ? function (event) {
  71148. try {
  71149. onProgress(event);
  71150. }
  71151. catch (e) {
  71152. errorHandler("Error in onProgress callback", e);
  71153. }
  71154. } : undefined;
  71155. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71156. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  71157. if (onSuccess) {
  71158. try {
  71159. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71160. }
  71161. catch (e) {
  71162. errorHandler("Error in onSuccess callback", e);
  71163. }
  71164. }
  71165. scene._removePendingData(loadingToken);
  71166. };
  71167. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71168. if (plugin.rewriteRootURL) {
  71169. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  71170. }
  71171. if (sceneFilename === "") {
  71172. if (sceneFilename === "") {
  71173. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71174. }
  71175. }
  71176. if (plugin.importMesh) {
  71177. var syncedPlugin = plugin;
  71178. var meshes = new Array();
  71179. var particleSystems = new Array();
  71180. var skeletons = new Array();
  71181. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71182. return;
  71183. }
  71184. scene.loadingPluginName = plugin.name;
  71185. successHandler(meshes, particleSystems, skeletons, []);
  71186. }
  71187. else {
  71188. var asyncedPlugin = plugin;
  71189. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (result) {
  71190. scene.loadingPluginName = plugin.name;
  71191. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71192. }).catch(function (error) {
  71193. errorHandler(error.message, error);
  71194. });
  71195. }
  71196. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71197. };
  71198. /**
  71199. * Import meshes into a scene
  71200. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71201. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71202. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71203. * @param scene the instance of BABYLON.Scene to append to
  71204. * @param onProgress a callback with a progress event for each file being loaded
  71205. * @param pluginExtension the extension used to determine the plugin
  71206. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71207. */
  71208. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71209. if (sceneFilename === void 0) { sceneFilename = ""; }
  71210. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71211. if (onProgress === void 0) { onProgress = null; }
  71212. if (pluginExtension === void 0) { pluginExtension = null; }
  71213. return new Promise(function (resolve, reject) {
  71214. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71215. resolve({
  71216. meshes: meshes,
  71217. particleSystems: particleSystems,
  71218. skeletons: skeletons,
  71219. animationGroups: animationGroups
  71220. });
  71221. }, onProgress, function (scene, message, exception) {
  71222. reject(exception || new Error(message));
  71223. }, pluginExtension);
  71224. });
  71225. };
  71226. /**
  71227. * Load a scene
  71228. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71229. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71230. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71231. * @param onSuccess a callback with the scene when import succeeds
  71232. * @param onProgress a callback with a progress event for each file being loaded
  71233. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71234. * @param pluginExtension the extension used to determine the plugin
  71235. * @returns The loaded plugin
  71236. */
  71237. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  71238. if (onSuccess === void 0) { onSuccess = null; }
  71239. if (onProgress === void 0) { onProgress = null; }
  71240. if (onError === void 0) { onError = null; }
  71241. if (pluginExtension === void 0) { pluginExtension = null; }
  71242. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  71243. };
  71244. /**
  71245. * Load a scene
  71246. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71247. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71248. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71249. * @param onProgress a callback with a progress event for each file being loaded
  71250. * @param pluginExtension the extension used to determine the plugin
  71251. * @returns The loaded scene
  71252. */
  71253. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  71254. if (onProgress === void 0) { onProgress = null; }
  71255. if (pluginExtension === void 0) { pluginExtension = null; }
  71256. return new Promise(function (resolve, reject) {
  71257. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  71258. resolve(scene);
  71259. }, onProgress, function (scene, message, exception) {
  71260. reject(exception || new Error(message));
  71261. }, pluginExtension);
  71262. });
  71263. };
  71264. /**
  71265. * Append a scene
  71266. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71267. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71268. * @param scene is the instance of BABYLON.Scene to append to
  71269. * @param onSuccess a callback with the scene when import succeeds
  71270. * @param onProgress a callback with a progress event for each file being loaded
  71271. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71272. * @param pluginExtension the extension used to determine the plugin
  71273. * @returns The loaded plugin
  71274. */
  71275. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71276. if (sceneFilename === void 0) { sceneFilename = ""; }
  71277. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71278. if (onSuccess === void 0) { onSuccess = null; }
  71279. if (onProgress === void 0) { onProgress = null; }
  71280. if (onError === void 0) { onError = null; }
  71281. if (pluginExtension === void 0) { pluginExtension = null; }
  71282. if (!scene) {
  71283. BABYLON.Tools.Error("No scene available to append to");
  71284. return null;
  71285. }
  71286. if (!sceneFilename) {
  71287. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71288. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71289. }
  71290. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71291. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71292. return null;
  71293. }
  71294. if (SceneLoader.ShowLoadingScreen) {
  71295. scene.getEngine().displayLoadingUI();
  71296. }
  71297. var loadingToken = {};
  71298. scene._addPendingData(loadingToken);
  71299. var disposeHandler = function () {
  71300. scene._removePendingData(loadingToken);
  71301. scene.getEngine().hideLoadingUI();
  71302. };
  71303. var errorHandler = function (message, exception) {
  71304. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71305. if (onError) {
  71306. onError(scene, errorMessage, exception);
  71307. }
  71308. else {
  71309. BABYLON.Tools.Error(errorMessage);
  71310. // should the exception be thrown?
  71311. }
  71312. disposeHandler();
  71313. };
  71314. var progressHandler = onProgress ? function (event) {
  71315. try {
  71316. onProgress(event);
  71317. }
  71318. catch (e) {
  71319. errorHandler("Error in onProgress callback", e);
  71320. }
  71321. } : undefined;
  71322. var successHandler = function () {
  71323. if (onSuccess) {
  71324. try {
  71325. onSuccess(scene);
  71326. }
  71327. catch (e) {
  71328. errorHandler("Error in onSuccess callback", e);
  71329. }
  71330. }
  71331. scene._removePendingData(loadingToken);
  71332. };
  71333. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71334. if (sceneFilename === "") {
  71335. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71336. }
  71337. if (plugin.load) {
  71338. var syncedPlugin = plugin;
  71339. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  71340. return;
  71341. }
  71342. scene.loadingPluginName = plugin.name;
  71343. successHandler();
  71344. }
  71345. else {
  71346. var asyncedPlugin = plugin;
  71347. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function () {
  71348. scene.loadingPluginName = plugin.name;
  71349. successHandler();
  71350. }).catch(function (error) {
  71351. errorHandler(error.message, error);
  71352. });
  71353. }
  71354. if (SceneLoader.ShowLoadingScreen) {
  71355. scene.executeWhenReady(function () {
  71356. scene.getEngine().hideLoadingUI();
  71357. });
  71358. }
  71359. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71360. };
  71361. /**
  71362. * Append a scene
  71363. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71364. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71365. * @param scene is the instance of BABYLON.Scene to append to
  71366. * @param onProgress a callback with a progress event for each file being loaded
  71367. * @param pluginExtension the extension used to determine the plugin
  71368. * @returns The given scene
  71369. */
  71370. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71371. if (sceneFilename === void 0) { sceneFilename = ""; }
  71372. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71373. if (onProgress === void 0) { onProgress = null; }
  71374. if (pluginExtension === void 0) { pluginExtension = null; }
  71375. return new Promise(function (resolve, reject) {
  71376. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71377. resolve(scene);
  71378. }, onProgress, function (scene, message, exception) {
  71379. reject(exception || new Error(message));
  71380. }, pluginExtension);
  71381. });
  71382. };
  71383. /**
  71384. * Load a scene into an asset container
  71385. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71386. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71387. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71388. * @param onSuccess a callback with the scene when import succeeds
  71389. * @param onProgress a callback with a progress event for each file being loaded
  71390. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71391. * @param pluginExtension the extension used to determine the plugin
  71392. * @returns The loaded plugin
  71393. */
  71394. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71395. if (sceneFilename === void 0) { sceneFilename = ""; }
  71396. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71397. if (onSuccess === void 0) { onSuccess = null; }
  71398. if (onProgress === void 0) { onProgress = null; }
  71399. if (onError === void 0) { onError = null; }
  71400. if (pluginExtension === void 0) { pluginExtension = null; }
  71401. if (!scene) {
  71402. BABYLON.Tools.Error("No scene available to load asset container to");
  71403. return null;
  71404. }
  71405. if (!sceneFilename) {
  71406. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71407. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71408. }
  71409. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71410. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71411. return null;
  71412. }
  71413. var loadingToken = {};
  71414. scene._addPendingData(loadingToken);
  71415. var disposeHandler = function () {
  71416. scene._removePendingData(loadingToken);
  71417. };
  71418. var errorHandler = function (message, exception) {
  71419. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71420. if (onError) {
  71421. onError(scene, errorMessage, exception);
  71422. }
  71423. else {
  71424. BABYLON.Tools.Error(errorMessage);
  71425. // should the exception be thrown?
  71426. }
  71427. disposeHandler();
  71428. };
  71429. var progressHandler = onProgress ? function (event) {
  71430. try {
  71431. onProgress(event);
  71432. }
  71433. catch (e) {
  71434. errorHandler("Error in onProgress callback", e);
  71435. }
  71436. } : undefined;
  71437. var successHandler = function (assets) {
  71438. if (onSuccess) {
  71439. try {
  71440. onSuccess(assets);
  71441. }
  71442. catch (e) {
  71443. errorHandler("Error in onSuccess callback", e);
  71444. }
  71445. }
  71446. scene._removePendingData(loadingToken);
  71447. };
  71448. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71449. if (plugin.loadAssetContainer) {
  71450. var syncedPlugin = plugin;
  71451. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71452. if (!assetContainer) {
  71453. return;
  71454. }
  71455. scene.loadingPluginName = plugin.name;
  71456. successHandler(assetContainer);
  71457. }
  71458. else if (plugin.loadAssetContainerAsync) {
  71459. var asyncedPlugin = plugin;
  71460. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (assetContainer) {
  71461. scene.loadingPluginName = plugin.name;
  71462. successHandler(assetContainer);
  71463. }).catch(function (error) {
  71464. errorHandler(error.message, error);
  71465. });
  71466. }
  71467. else {
  71468. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71469. }
  71470. if (SceneLoader.ShowLoadingScreen) {
  71471. scene.executeWhenReady(function () {
  71472. scene.getEngine().hideLoadingUI();
  71473. });
  71474. }
  71475. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71476. };
  71477. /**
  71478. * Load a scene into an asset container
  71479. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71480. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71481. * @param scene is the instance of BABYLON.Scene to append to
  71482. * @param onProgress a callback with a progress event for each file being loaded
  71483. * @param pluginExtension the extension used to determine the plugin
  71484. * @returns The loaded asset container
  71485. */
  71486. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71487. if (sceneFilename === void 0) { sceneFilename = ""; }
  71488. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71489. if (onProgress === void 0) { onProgress = null; }
  71490. if (pluginExtension === void 0) { pluginExtension = null; }
  71491. return new Promise(function (resolve, reject) {
  71492. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71493. resolve(assetContainer);
  71494. }, onProgress, function (scene, message, exception) {
  71495. reject(exception || new Error(message));
  71496. }, pluginExtension);
  71497. });
  71498. };
  71499. // Flags
  71500. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71501. SceneLoader._ShowLoadingScreen = true;
  71502. SceneLoader._CleanBoneMatrixWeights = false;
  71503. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71504. // Members
  71505. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71506. SceneLoader._registeredPlugins = {};
  71507. return SceneLoader;
  71508. }());
  71509. BABYLON.SceneLoader = SceneLoader;
  71510. ;
  71511. })(BABYLON || (BABYLON = {}));
  71512. //# sourceMappingURL=babylon.sceneLoader.js.map
  71513. var BABYLON;
  71514. (function (BABYLON) {
  71515. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71516. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71517. var parsedMaterial = parsedData.materials[index];
  71518. if (parsedMaterial.id === id) {
  71519. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71520. }
  71521. }
  71522. return null;
  71523. };
  71524. var isDescendantOf = function (mesh, names, hierarchyIds) {
  71525. for (var i in names) {
  71526. if (mesh.name === names[i]) {
  71527. hierarchyIds.push(mesh.id);
  71528. return true;
  71529. }
  71530. }
  71531. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  71532. hierarchyIds.push(mesh.id);
  71533. return true;
  71534. }
  71535. return false;
  71536. };
  71537. var logOperation = function (operation, producer) {
  71538. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  71539. };
  71540. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71541. if (addToScene === void 0) { addToScene = false; }
  71542. var container = new BABYLON.AssetContainer(scene);
  71543. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71544. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71545. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71546. // and avoid problems with multiple concurrent .babylon loads.
  71547. var log = "importScene has failed JSON parse";
  71548. try {
  71549. var parsedData = JSON.parse(data);
  71550. log = "";
  71551. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71552. var index;
  71553. var cache;
  71554. // Lights
  71555. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  71556. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  71557. var parsedLight = parsedData.lights[index];
  71558. var light = BABYLON.Light.Parse(parsedLight, scene);
  71559. if (light) {
  71560. container.lights.push(light);
  71561. log += (index === 0 ? "\n\tLights:" : "");
  71562. log += "\n\t\t" + light.toString(fullDetails);
  71563. }
  71564. }
  71565. }
  71566. // Animations
  71567. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71568. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71569. var parsedAnimation = parsedData.animations[index];
  71570. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71571. scene.animations.push(animation);
  71572. container.animations.push(animation);
  71573. log += (index === 0 ? "\n\tAnimations:" : "");
  71574. log += "\n\t\t" + animation.toString(fullDetails);
  71575. }
  71576. }
  71577. // Materials
  71578. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  71579. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71580. var parsedMaterial = parsedData.materials[index];
  71581. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71582. container.materials.push(mat);
  71583. log += (index === 0 ? "\n\tMaterials:" : "");
  71584. log += "\n\t\t" + mat.toString(fullDetails);
  71585. }
  71586. }
  71587. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71588. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  71589. var parsedMultiMaterial = parsedData.multiMaterials[index];
  71590. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71591. container.multiMaterials.push(mmat);
  71592. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  71593. log += "\n\t\t" + mmat.toString(fullDetails);
  71594. }
  71595. }
  71596. // Morph targets
  71597. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71598. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71599. var managerData = _a[_i];
  71600. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  71601. }
  71602. }
  71603. // Skeletons
  71604. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71605. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  71606. var parsedSkeleton = parsedData.skeletons[index];
  71607. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71608. container.skeletons.push(skeleton);
  71609. log += (index === 0 ? "\n\tSkeletons:" : "");
  71610. log += "\n\t\t" + skeleton.toString(fullDetails);
  71611. }
  71612. }
  71613. // Geometries
  71614. var geometries = parsedData.geometries;
  71615. if (geometries !== undefined && geometries !== null) {
  71616. var addedGeometry = new Array();
  71617. // Boxes
  71618. var boxes = geometries.boxes;
  71619. if (boxes !== undefined && boxes !== null) {
  71620. for (index = 0, cache = boxes.length; index < cache; index++) {
  71621. var parsedBox = boxes[index];
  71622. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71623. }
  71624. }
  71625. // Spheres
  71626. var spheres = geometries.spheres;
  71627. if (spheres !== undefined && spheres !== null) {
  71628. for (index = 0, cache = spheres.length; index < cache; index++) {
  71629. var parsedSphere = spheres[index];
  71630. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71631. }
  71632. }
  71633. // Cylinders
  71634. var cylinders = geometries.cylinders;
  71635. if (cylinders !== undefined && cylinders !== null) {
  71636. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71637. var parsedCylinder = cylinders[index];
  71638. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71639. }
  71640. }
  71641. // Toruses
  71642. var toruses = geometries.toruses;
  71643. if (toruses !== undefined && toruses !== null) {
  71644. for (index = 0, cache = toruses.length; index < cache; index++) {
  71645. var parsedTorus = toruses[index];
  71646. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71647. }
  71648. }
  71649. // Grounds
  71650. var grounds = geometries.grounds;
  71651. if (grounds !== undefined && grounds !== null) {
  71652. for (index = 0, cache = grounds.length; index < cache; index++) {
  71653. var parsedGround = grounds[index];
  71654. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71655. }
  71656. }
  71657. // Planes
  71658. var planes = geometries.planes;
  71659. if (planes !== undefined && planes !== null) {
  71660. for (index = 0, cache = planes.length; index < cache; index++) {
  71661. var parsedPlane = planes[index];
  71662. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71663. }
  71664. }
  71665. // TorusKnots
  71666. var torusKnots = geometries.torusKnots;
  71667. if (torusKnots !== undefined && torusKnots !== null) {
  71668. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71669. var parsedTorusKnot = torusKnots[index];
  71670. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71671. }
  71672. }
  71673. // VertexData
  71674. var vertexData = geometries.vertexData;
  71675. if (vertexData !== undefined && vertexData !== null) {
  71676. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71677. var parsedVertexData = vertexData[index];
  71678. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71679. }
  71680. }
  71681. addedGeometry.forEach(function (g) {
  71682. if (g) {
  71683. container.geometries.push(g);
  71684. }
  71685. });
  71686. }
  71687. // Transform nodes
  71688. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71689. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71690. var parsedTransformNode = parsedData.transformNodes[index];
  71691. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71692. container.transformNodes.push(node);
  71693. }
  71694. }
  71695. // Meshes
  71696. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71697. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71698. var parsedMesh = parsedData.meshes[index];
  71699. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71700. container.meshes.push(mesh);
  71701. log += (index === 0 ? "\n\tMeshes:" : "");
  71702. log += "\n\t\t" + mesh.toString(fullDetails);
  71703. }
  71704. }
  71705. // Cameras
  71706. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71707. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71708. var parsedCamera = parsedData.cameras[index];
  71709. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71710. container.cameras.push(camera);
  71711. log += (index === 0 ? "\n\tCameras:" : "");
  71712. log += "\n\t\t" + camera.toString(fullDetails);
  71713. }
  71714. }
  71715. // Browsing all the graph to connect the dots
  71716. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71717. var camera = scene.cameras[index];
  71718. if (camera._waitingParentId) {
  71719. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71720. camera._waitingParentId = null;
  71721. }
  71722. }
  71723. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71724. var light_1 = scene.lights[index];
  71725. if (light_1 && light_1._waitingParentId) {
  71726. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71727. light_1._waitingParentId = null;
  71728. }
  71729. }
  71730. // Sounds
  71731. // TODO: add sound
  71732. var loadedSounds = [];
  71733. var loadedSound;
  71734. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71735. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71736. var parsedSound = parsedData.sounds[index];
  71737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71738. if (!parsedSound.url)
  71739. parsedSound.url = parsedSound.name;
  71740. if (!loadedSounds[parsedSound.url]) {
  71741. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71742. loadedSounds[parsedSound.url] = loadedSound;
  71743. container.sounds.push(loadedSound);
  71744. }
  71745. else {
  71746. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71747. }
  71748. }
  71749. else {
  71750. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71751. }
  71752. }
  71753. }
  71754. loadedSounds = [];
  71755. // Connect parents & children and parse actions
  71756. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71757. var transformNode = scene.transformNodes[index];
  71758. if (transformNode._waitingParentId) {
  71759. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71760. transformNode._waitingParentId = null;
  71761. }
  71762. }
  71763. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71764. var mesh = scene.meshes[index];
  71765. if (mesh._waitingParentId) {
  71766. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71767. mesh._waitingParentId = null;
  71768. }
  71769. if (mesh._waitingActions) {
  71770. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71771. mesh._waitingActions = null;
  71772. }
  71773. }
  71774. // freeze world matrix application
  71775. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71776. var currentMesh = scene.meshes[index];
  71777. if (currentMesh._waitingFreezeWorldMatrix) {
  71778. currentMesh.freezeWorldMatrix();
  71779. currentMesh._waitingFreezeWorldMatrix = null;
  71780. }
  71781. else {
  71782. currentMesh.computeWorldMatrix(true);
  71783. }
  71784. }
  71785. // Lights exclusions / inclusions
  71786. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71787. var light_2 = scene.lights[index];
  71788. // Excluded check
  71789. if (light_2._excludedMeshesIds.length > 0) {
  71790. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71791. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71792. if (excludedMesh) {
  71793. light_2.excludedMeshes.push(excludedMesh);
  71794. }
  71795. }
  71796. light_2._excludedMeshesIds = [];
  71797. }
  71798. // Included check
  71799. if (light_2._includedOnlyMeshesIds.length > 0) {
  71800. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71801. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71802. if (includedOnlyMesh) {
  71803. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71804. }
  71805. }
  71806. light_2._includedOnlyMeshesIds = [];
  71807. }
  71808. }
  71809. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71810. // Actions (scene)
  71811. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71812. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71813. }
  71814. if (!addToScene) {
  71815. container.removeAllFromScene();
  71816. }
  71817. }
  71818. catch (err) {
  71819. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  71820. if (onError) {
  71821. onError(msg, err);
  71822. }
  71823. else {
  71824. BABYLON.Tools.Log(msg);
  71825. throw err;
  71826. }
  71827. }
  71828. finally {
  71829. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71830. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71831. }
  71832. }
  71833. return container;
  71834. };
  71835. BABYLON.SceneLoader.RegisterPlugin({
  71836. name: "babylon.js",
  71837. extensions: ".babylon",
  71838. canDirectLoad: function (data) {
  71839. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71840. return true;
  71841. }
  71842. return false;
  71843. },
  71844. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71845. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71846. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71847. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71848. // and avoid problems with multiple concurrent .babylon loads.
  71849. var log = "importMesh has failed JSON parse";
  71850. try {
  71851. var parsedData = JSON.parse(data);
  71852. log = "";
  71853. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71854. if (!meshesNames) {
  71855. meshesNames = null;
  71856. }
  71857. else if (!Array.isArray(meshesNames)) {
  71858. meshesNames = [meshesNames];
  71859. }
  71860. var hierarchyIds = new Array();
  71861. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71862. var loadedSkeletonsIds = [];
  71863. var loadedMaterialsIds = [];
  71864. var index;
  71865. var cache;
  71866. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71867. var parsedMesh = parsedData.meshes[index];
  71868. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71869. if (meshesNames !== null) {
  71870. // Remove found mesh name from list.
  71871. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71872. }
  71873. //Geometry?
  71874. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71875. //does the file contain geometries?
  71876. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71877. //find the correct geometry and add it to the scene
  71878. var found = false;
  71879. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71880. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71881. return;
  71882. }
  71883. else {
  71884. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71885. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71886. switch (geometryType) {
  71887. case "boxes":
  71888. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71889. break;
  71890. case "spheres":
  71891. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71892. break;
  71893. case "cylinders":
  71894. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71895. break;
  71896. case "toruses":
  71897. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71898. break;
  71899. case "grounds":
  71900. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71901. break;
  71902. case "planes":
  71903. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71904. break;
  71905. case "torusKnots":
  71906. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71907. break;
  71908. case "vertexData":
  71909. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71910. break;
  71911. }
  71912. found = true;
  71913. }
  71914. });
  71915. }
  71916. });
  71917. if (found === false) {
  71918. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71919. }
  71920. }
  71921. }
  71922. // Material ?
  71923. if (parsedMesh.materialId) {
  71924. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71925. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71926. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71927. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71928. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71929. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71930. var subMatId = parsedMultiMaterial.materials[matIndex];
  71931. loadedMaterialsIds.push(subMatId);
  71932. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71933. if (mat) {
  71934. log += "\n\tMaterial " + mat.toString(fullDetails);
  71935. }
  71936. }
  71937. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71938. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71939. if (mmat) {
  71940. materialFound = true;
  71941. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71942. }
  71943. break;
  71944. }
  71945. }
  71946. }
  71947. if (materialFound === false) {
  71948. loadedMaterialsIds.push(parsedMesh.materialId);
  71949. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71950. if (!mat) {
  71951. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71952. }
  71953. else {
  71954. log += "\n\tMaterial " + mat.toString(fullDetails);
  71955. }
  71956. }
  71957. }
  71958. // Skeleton ?
  71959. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71960. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71961. if (skeletonAlreadyLoaded === false) {
  71962. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71963. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71964. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71965. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71966. skeletons.push(skeleton);
  71967. loadedSkeletonsIds.push(parsedSkeleton.id);
  71968. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71969. }
  71970. }
  71971. }
  71972. }
  71973. // Morph targets ?
  71974. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71975. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71976. var managerData = _a[_i];
  71977. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71978. }
  71979. }
  71980. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71981. meshes.push(mesh);
  71982. log += "\n\tMesh " + mesh.toString(fullDetails);
  71983. }
  71984. }
  71985. // Connecting parents
  71986. var currentMesh;
  71987. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71988. currentMesh = scene.meshes[index];
  71989. if (currentMesh._waitingParentId) {
  71990. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71991. currentMesh._waitingParentId = null;
  71992. }
  71993. }
  71994. // freeze and compute world matrix application
  71995. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71996. currentMesh = scene.meshes[index];
  71997. if (currentMesh._waitingFreezeWorldMatrix) {
  71998. currentMesh.freezeWorldMatrix();
  71999. currentMesh._waitingFreezeWorldMatrix = null;
  72000. }
  72001. else {
  72002. currentMesh.computeWorldMatrix(true);
  72003. }
  72004. }
  72005. }
  72006. // Particles
  72007. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72008. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72009. if (parser) {
  72010. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72011. var parsedParticleSystem = parsedData.particleSystems[index];
  72012. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72013. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72014. }
  72015. }
  72016. }
  72017. }
  72018. return true;
  72019. }
  72020. catch (err) {
  72021. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72022. if (onError) {
  72023. onError(msg, err);
  72024. }
  72025. else {
  72026. BABYLON.Tools.Log(msg);
  72027. throw err;
  72028. }
  72029. }
  72030. finally {
  72031. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72032. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72033. }
  72034. }
  72035. return false;
  72036. },
  72037. load: function (scene, data, rootUrl, onError) {
  72038. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72039. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72040. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72041. // and avoid problems with multiple concurrent .babylon loads.
  72042. var log = "importScene has failed JSON parse";
  72043. try {
  72044. var parsedData = JSON.parse(data);
  72045. log = "";
  72046. // Scene
  72047. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72048. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72049. }
  72050. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72051. scene.autoClear = parsedData.autoClear;
  72052. }
  72053. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72054. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72055. }
  72056. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72057. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72058. }
  72059. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72060. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72061. }
  72062. // Fog
  72063. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72064. scene.fogMode = parsedData.fogMode;
  72065. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72066. scene.fogStart = parsedData.fogStart;
  72067. scene.fogEnd = parsedData.fogEnd;
  72068. scene.fogDensity = parsedData.fogDensity;
  72069. log += "\tFog mode for scene: ";
  72070. switch (scene.fogMode) {
  72071. // getters not compiling, so using hardcoded
  72072. case 1:
  72073. log += "exp\n";
  72074. break;
  72075. case 2:
  72076. log += "exp2\n";
  72077. break;
  72078. case 3:
  72079. log += "linear\n";
  72080. break;
  72081. }
  72082. }
  72083. //Physics
  72084. if (parsedData.physicsEnabled) {
  72085. var physicsPlugin;
  72086. if (parsedData.physicsEngine === "cannon") {
  72087. physicsPlugin = new BABYLON.CannonJSPlugin();
  72088. }
  72089. else if (parsedData.physicsEngine === "oimo") {
  72090. physicsPlugin = new BABYLON.OimoJSPlugin();
  72091. }
  72092. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72093. //else - default engine, which is currently oimo
  72094. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72095. scene.enablePhysics(physicsGravity, physicsPlugin);
  72096. }
  72097. // Metadata
  72098. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72099. scene.metadata = parsedData.metadata;
  72100. }
  72101. //collisions, if defined. otherwise, default is true
  72102. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72103. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72104. }
  72105. scene.workerCollisions = !!parsedData.workerCollisions;
  72106. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72107. if (!container) {
  72108. return false;
  72109. }
  72110. if (parsedData.autoAnimate) {
  72111. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72112. }
  72113. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72114. scene.setActiveCameraByID(parsedData.activeCameraID);
  72115. }
  72116. // Environment texture
  72117. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72118. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72119. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72120. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72121. if (parsedData.environmentTextureRotationY) {
  72122. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72123. }
  72124. scene.environmentTexture = hdrTexture;
  72125. }
  72126. else {
  72127. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72128. if (parsedData.environmentTextureRotationY) {
  72129. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72130. }
  72131. scene.environmentTexture = cubeTexture;
  72132. }
  72133. if (parsedData.createDefaultSkybox === true) {
  72134. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72135. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72136. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72137. }
  72138. }
  72139. // Finish
  72140. return true;
  72141. }
  72142. catch (err) {
  72143. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72144. if (onError) {
  72145. onError(msg, err);
  72146. }
  72147. else {
  72148. BABYLON.Tools.Log(msg);
  72149. throw err;
  72150. }
  72151. }
  72152. finally {
  72153. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72154. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72155. }
  72156. }
  72157. return false;
  72158. },
  72159. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72160. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72161. return container;
  72162. }
  72163. });
  72164. })(BABYLON || (BABYLON = {}));
  72165. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72166. var BABYLON;
  72167. (function (BABYLON) {
  72168. var FilesInput = /** @class */ (function () {
  72169. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72170. this.onProcessFileCallback = function () { return true; };
  72171. this._engine = engine;
  72172. this._currentScene = scene;
  72173. this._sceneLoadedCallback = sceneLoadedCallback;
  72174. this._progressCallback = progressCallback;
  72175. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72176. this._textureLoadingCallback = textureLoadingCallback;
  72177. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72178. this._onReloadCallback = onReloadCallback;
  72179. this._errorCallback = errorCallback;
  72180. }
  72181. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72182. var _this = this;
  72183. if (elementToMonitor) {
  72184. this._elementToMonitor = elementToMonitor;
  72185. this._dragEnterHandler = function (e) { _this.drag(e); };
  72186. this._dragOverHandler = function (e) { _this.drag(e); };
  72187. this._dropHandler = function (e) { _this.drop(e); };
  72188. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72189. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72190. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72191. }
  72192. };
  72193. FilesInput.prototype.dispose = function () {
  72194. if (!this._elementToMonitor) {
  72195. return;
  72196. }
  72197. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72198. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72199. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72200. };
  72201. FilesInput.prototype.renderFunction = function () {
  72202. if (this._additionalRenderLoopLogicCallback) {
  72203. this._additionalRenderLoopLogicCallback();
  72204. }
  72205. if (this._currentScene) {
  72206. if (this._textureLoadingCallback) {
  72207. var remaining = this._currentScene.getWaitingItemsCount();
  72208. if (remaining > 0) {
  72209. this._textureLoadingCallback(remaining);
  72210. }
  72211. }
  72212. this._currentScene.render();
  72213. }
  72214. };
  72215. FilesInput.prototype.drag = function (e) {
  72216. e.stopPropagation();
  72217. e.preventDefault();
  72218. };
  72219. FilesInput.prototype.drop = function (eventDrop) {
  72220. eventDrop.stopPropagation();
  72221. eventDrop.preventDefault();
  72222. this.loadFiles(eventDrop);
  72223. };
  72224. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72225. var _this = this;
  72226. var reader = folder.createReader();
  72227. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72228. reader.readEntries(function (entries) {
  72229. remaining.count += entries.length;
  72230. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72231. var entry = entries_1[_i];
  72232. if (entry.isFile) {
  72233. entry.file(function (file) {
  72234. file.correctName = relativePath + file.name;
  72235. files.push(file);
  72236. if (--remaining.count === 0) {
  72237. callback();
  72238. }
  72239. });
  72240. }
  72241. else if (entry.isDirectory) {
  72242. _this._traverseFolder(entry, files, remaining, callback);
  72243. }
  72244. }
  72245. if (--remaining.count) {
  72246. callback();
  72247. }
  72248. });
  72249. };
  72250. FilesInput.prototype._processFiles = function (files) {
  72251. for (var i = 0; i < files.length; i++) {
  72252. var name = files[i].correctName.toLowerCase();
  72253. var extension = name.split('.').pop();
  72254. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72255. continue;
  72256. }
  72257. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  72258. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  72259. this._sceneFileToLoad = files[i];
  72260. }
  72261. else {
  72262. FilesInput.FilesToLoad[name] = files[i];
  72263. }
  72264. }
  72265. };
  72266. FilesInput.prototype.loadFiles = function (event) {
  72267. var _this = this;
  72268. // Handling data transfer via drag'n'drop
  72269. if (event && event.dataTransfer && event.dataTransfer.files) {
  72270. this._filesToLoad = event.dataTransfer.files;
  72271. }
  72272. // Handling files from input files
  72273. if (event && event.target && event.target.files) {
  72274. this._filesToLoad = event.target.files;
  72275. }
  72276. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  72277. return;
  72278. }
  72279. if (this._startingProcessingFilesCallback) {
  72280. this._startingProcessingFilesCallback(this._filesToLoad);
  72281. }
  72282. if (this._filesToLoad && this._filesToLoad.length > 0) {
  72283. var files_1 = new Array();
  72284. var folders = [];
  72285. var items = event.dataTransfer ? event.dataTransfer.items : null;
  72286. for (var i = 0; i < this._filesToLoad.length; i++) {
  72287. var fileToLoad = this._filesToLoad[i];
  72288. var name_1 = fileToLoad.name.toLowerCase();
  72289. var entry = void 0;
  72290. fileToLoad.correctName = name_1;
  72291. if (items) {
  72292. var item = items[i];
  72293. if (item.getAsEntry) {
  72294. entry = item.getAsEntry();
  72295. }
  72296. else if (item.webkitGetAsEntry) {
  72297. entry = item.webkitGetAsEntry();
  72298. }
  72299. }
  72300. if (!entry) {
  72301. files_1.push(fileToLoad);
  72302. }
  72303. else {
  72304. if (entry.isDirectory) {
  72305. folders.push(entry);
  72306. }
  72307. else {
  72308. files_1.push(fileToLoad);
  72309. }
  72310. }
  72311. }
  72312. if (folders.length === 0) {
  72313. this._processFiles(files_1);
  72314. this._processReload();
  72315. }
  72316. else {
  72317. var remaining = { count: folders.length };
  72318. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  72319. var folder = folders_1[_i];
  72320. this._traverseFolder(folder, files_1, remaining, function () {
  72321. _this._processFiles(files_1);
  72322. if (remaining.count === 0) {
  72323. _this._processReload();
  72324. }
  72325. });
  72326. }
  72327. }
  72328. }
  72329. };
  72330. FilesInput.prototype._processReload = function () {
  72331. if (this._onReloadCallback) {
  72332. this._onReloadCallback(this._sceneFileToLoad);
  72333. }
  72334. else {
  72335. this.reload();
  72336. }
  72337. };
  72338. FilesInput.prototype.reload = function () {
  72339. var _this = this;
  72340. // If a scene file has been provided
  72341. if (this._sceneFileToLoad) {
  72342. if (this._currentScene) {
  72343. if (BABYLON.Tools.errorsCount > 0) {
  72344. BABYLON.Tools.ClearLogCache();
  72345. }
  72346. this._engine.stopRenderLoop();
  72347. }
  72348. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  72349. if (_this._progressCallback) {
  72350. _this._progressCallback(progress);
  72351. }
  72352. }).then(function (scene) {
  72353. if (_this._currentScene) {
  72354. _this._currentScene.dispose();
  72355. }
  72356. _this._currentScene = scene;
  72357. if (_this._sceneLoadedCallback) {
  72358. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  72359. }
  72360. // Wait for textures and shaders to be ready
  72361. _this._currentScene.executeWhenReady(function () {
  72362. _this._engine.runRenderLoop(function () {
  72363. _this.renderFunction();
  72364. });
  72365. });
  72366. }).catch(function (error) {
  72367. if (_this._errorCallback) {
  72368. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72369. }
  72370. });
  72371. }
  72372. else {
  72373. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72374. }
  72375. };
  72376. FilesInput.FilesToLoad = {};
  72377. return FilesInput;
  72378. }());
  72379. BABYLON.FilesInput = FilesInput;
  72380. })(BABYLON || (BABYLON = {}));
  72381. //# sourceMappingURL=babylon.filesInput.js.map
  72382. var BABYLON;
  72383. (function (BABYLON) {
  72384. var Tags = /** @class */ (function () {
  72385. function Tags() {
  72386. }
  72387. Tags.EnableFor = function (obj) {
  72388. obj._tags = obj._tags || {};
  72389. obj.hasTags = function () {
  72390. return Tags.HasTags(obj);
  72391. };
  72392. obj.addTags = function (tagsString) {
  72393. return Tags.AddTagsTo(obj, tagsString);
  72394. };
  72395. obj.removeTags = function (tagsString) {
  72396. return Tags.RemoveTagsFrom(obj, tagsString);
  72397. };
  72398. obj.matchesTagsQuery = function (tagsQuery) {
  72399. return Tags.MatchesQuery(obj, tagsQuery);
  72400. };
  72401. };
  72402. Tags.DisableFor = function (obj) {
  72403. delete obj._tags;
  72404. delete obj.hasTags;
  72405. delete obj.addTags;
  72406. delete obj.removeTags;
  72407. delete obj.matchesTagsQuery;
  72408. };
  72409. Tags.HasTags = function (obj) {
  72410. if (!obj._tags) {
  72411. return false;
  72412. }
  72413. return !BABYLON.Tools.IsEmpty(obj._tags);
  72414. };
  72415. Tags.GetTags = function (obj, asString) {
  72416. if (asString === void 0) { asString = true; }
  72417. if (!obj._tags) {
  72418. return null;
  72419. }
  72420. if (asString) {
  72421. var tagsArray = [];
  72422. for (var tag in obj._tags) {
  72423. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72424. tagsArray.push(tag);
  72425. }
  72426. }
  72427. return tagsArray.join(" ");
  72428. }
  72429. else {
  72430. return obj._tags;
  72431. }
  72432. };
  72433. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72434. // a tag cannot start with '||', '&&', and '!'
  72435. // it cannot contain whitespaces
  72436. Tags.AddTagsTo = function (obj, tagsString) {
  72437. if (!tagsString) {
  72438. return;
  72439. }
  72440. if (typeof tagsString !== "string") {
  72441. return;
  72442. }
  72443. var tags = tagsString.split(" ");
  72444. tags.forEach(function (tag, index, array) {
  72445. Tags._AddTagTo(obj, tag);
  72446. });
  72447. };
  72448. Tags._AddTagTo = function (obj, tag) {
  72449. tag = tag.trim();
  72450. if (tag === "" || tag === "true" || tag === "false") {
  72451. return;
  72452. }
  72453. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72454. return;
  72455. }
  72456. Tags.EnableFor(obj);
  72457. obj._tags[tag] = true;
  72458. };
  72459. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72460. if (!Tags.HasTags(obj)) {
  72461. return;
  72462. }
  72463. var tags = tagsString.split(" ");
  72464. for (var t in tags) {
  72465. Tags._RemoveTagFrom(obj, tags[t]);
  72466. }
  72467. };
  72468. Tags._RemoveTagFrom = function (obj, tag) {
  72469. delete obj._tags[tag];
  72470. };
  72471. Tags.MatchesQuery = function (obj, tagsQuery) {
  72472. if (tagsQuery === undefined) {
  72473. return true;
  72474. }
  72475. if (tagsQuery === "") {
  72476. return Tags.HasTags(obj);
  72477. }
  72478. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72479. };
  72480. return Tags;
  72481. }());
  72482. BABYLON.Tags = Tags;
  72483. })(BABYLON || (BABYLON = {}));
  72484. //# sourceMappingURL=babylon.tags.js.map
  72485. var BABYLON;
  72486. (function (BABYLON) {
  72487. /**
  72488. * Class used to evalaute queries containing `and` and `or` operators
  72489. */
  72490. var AndOrNotEvaluator = /** @class */ (function () {
  72491. function AndOrNotEvaluator() {
  72492. }
  72493. /**
  72494. * Evaluate a query
  72495. * @param query defines the query to evaluate
  72496. * @param evaluateCallback defines the callback used to filter result
  72497. * @returns true if the query matches
  72498. */
  72499. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72500. if (!query.match(/\([^\(\)]*\)/g)) {
  72501. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72502. }
  72503. else {
  72504. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72505. // remove parenthesis
  72506. r = r.slice(1, r.length - 1);
  72507. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72508. });
  72509. }
  72510. if (query === "true") {
  72511. return true;
  72512. }
  72513. if (query === "false") {
  72514. return false;
  72515. }
  72516. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72517. };
  72518. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  72519. evaluateCallback = evaluateCallback || (function (r) {
  72520. return r === "true" ? true : false;
  72521. });
  72522. var result;
  72523. var or = parenthesisContent.split("||");
  72524. for (var i in or) {
  72525. if (or.hasOwnProperty(i)) {
  72526. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  72527. var and = ori.split("&&");
  72528. if (and.length > 1) {
  72529. for (var j = 0; j < and.length; ++j) {
  72530. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  72531. if (andj !== "true" && andj !== "false") {
  72532. if (andj[0] === "!") {
  72533. result = !evaluateCallback(andj.substring(1));
  72534. }
  72535. else {
  72536. result = evaluateCallback(andj);
  72537. }
  72538. }
  72539. else {
  72540. result = andj === "true" ? true : false;
  72541. }
  72542. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72543. ori = "false";
  72544. break;
  72545. }
  72546. }
  72547. }
  72548. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72549. result = true;
  72550. break;
  72551. }
  72552. // result equals false (or undefined)
  72553. if (ori !== "true" && ori !== "false") {
  72554. if (ori[0] === "!") {
  72555. result = !evaluateCallback(ori.substring(1));
  72556. }
  72557. else {
  72558. result = evaluateCallback(ori);
  72559. }
  72560. }
  72561. else {
  72562. result = ori === "true" ? true : false;
  72563. }
  72564. }
  72565. }
  72566. // the whole parenthesis scope is replaced by 'true' or 'false'
  72567. return result ? "true" : "false";
  72568. };
  72569. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72570. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72571. // remove whitespaces
  72572. r = r.replace(/[\s]/g, function () { return ""; });
  72573. return r.length % 2 ? "!" : "";
  72574. });
  72575. booleanString = booleanString.trim();
  72576. if (booleanString === "!true") {
  72577. booleanString = "false";
  72578. }
  72579. else if (booleanString === "!false") {
  72580. booleanString = "true";
  72581. }
  72582. return booleanString;
  72583. };
  72584. return AndOrNotEvaluator;
  72585. }());
  72586. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  72587. })(BABYLON || (BABYLON = {}));
  72588. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  72589. var BABYLON;
  72590. (function (BABYLON) {
  72591. /**
  72592. * Class used to enable access to IndexedDB
  72593. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  72594. */
  72595. var Database = /** @class */ (function () {
  72596. /**
  72597. * Creates a new Database
  72598. * @param urlToScene defines the url to load the scene
  72599. * @param callbackManifestChecked defines the callback to use when manifest is checked
  72600. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  72601. */
  72602. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  72603. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  72604. var _this = this;
  72605. // Handling various flavors of prefixed version of IndexedDB
  72606. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  72607. this.callbackManifestChecked = callbackManifestChecked;
  72608. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  72609. this.db = null;
  72610. this._enableSceneOffline = false;
  72611. this._enableTexturesOffline = false;
  72612. this.manifestVersionFound = 0;
  72613. this.mustUpdateRessources = false;
  72614. this.hasReachedQuota = false;
  72615. if (!Database.IDBStorageEnabled) {
  72616. this.callbackManifestChecked(true);
  72617. }
  72618. else {
  72619. if (disableManifestCheck) {
  72620. this._enableSceneOffline = true;
  72621. this._enableTexturesOffline = true;
  72622. this.manifestVersionFound = 1;
  72623. BABYLON.Tools.SetImmediate(function () {
  72624. _this.callbackManifestChecked(true);
  72625. });
  72626. }
  72627. else {
  72628. this._checkManifestFile();
  72629. }
  72630. }
  72631. }
  72632. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72633. /**
  72634. * Gets a boolean indicating if scene must be saved in the database
  72635. */
  72636. get: function () {
  72637. return this._enableSceneOffline;
  72638. },
  72639. enumerable: true,
  72640. configurable: true
  72641. });
  72642. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72643. /**
  72644. * Gets a boolean indicating if textures must be saved in the database
  72645. */
  72646. get: function () {
  72647. return this._enableTexturesOffline;
  72648. },
  72649. enumerable: true,
  72650. configurable: true
  72651. });
  72652. Database.prototype._checkManifestFile = function () {
  72653. var _this = this;
  72654. var noManifestFile = function () {
  72655. _this._enableSceneOffline = false;
  72656. _this._enableTexturesOffline = false;
  72657. _this.callbackManifestChecked(false);
  72658. };
  72659. var timeStampUsed = false;
  72660. var manifestURL = this.currentSceneUrl + ".manifest";
  72661. var xhr = new XMLHttpRequest();
  72662. if (navigator.onLine) {
  72663. // Adding a timestamp to by-pass browsers' cache
  72664. timeStampUsed = true;
  72665. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72666. }
  72667. xhr.open("GET", manifestURL, true);
  72668. xhr.addEventListener("load", function () {
  72669. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72670. try {
  72671. var manifestFile = JSON.parse(xhr.response);
  72672. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72673. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72674. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72675. _this.manifestVersionFound = manifestFile.version;
  72676. }
  72677. if (_this.callbackManifestChecked) {
  72678. _this.callbackManifestChecked(true);
  72679. }
  72680. }
  72681. catch (ex) {
  72682. noManifestFile();
  72683. }
  72684. }
  72685. else {
  72686. noManifestFile();
  72687. }
  72688. }, false);
  72689. xhr.addEventListener("error", function (event) {
  72690. if (timeStampUsed) {
  72691. timeStampUsed = false;
  72692. // Let's retry without the timeStamp
  72693. // It could fail when coupled with HTML5 Offline API
  72694. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72695. xhr.open("GET", retryManifestURL, true);
  72696. xhr.send();
  72697. }
  72698. else {
  72699. noManifestFile();
  72700. }
  72701. }, false);
  72702. try {
  72703. xhr.send();
  72704. }
  72705. catch (ex) {
  72706. BABYLON.Tools.Error("Error on XHR send request.");
  72707. this.callbackManifestChecked(false);
  72708. }
  72709. };
  72710. /**
  72711. * Open the database and make it available
  72712. * @param successCallback defines the callback to call on success
  72713. * @param errorCallback defines the callback to call on error
  72714. */
  72715. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72716. var _this = this;
  72717. var handleError = function () {
  72718. _this.isSupported = false;
  72719. if (errorCallback)
  72720. errorCallback();
  72721. };
  72722. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72723. // Your browser doesn't support IndexedDB
  72724. this.isSupported = false;
  72725. if (errorCallback)
  72726. errorCallback();
  72727. }
  72728. else {
  72729. // If the DB hasn't been opened or created yet
  72730. if (!this.db) {
  72731. this.hasReachedQuota = false;
  72732. this.isSupported = true;
  72733. var request = this.idbFactory.open("babylonjs", 1);
  72734. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72735. request.onerror = function (event) {
  72736. handleError();
  72737. };
  72738. // executes when a version change transaction cannot complete due to other active transactions
  72739. request.onblocked = function (event) {
  72740. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72741. handleError();
  72742. };
  72743. // DB has been opened successfully
  72744. request.onsuccess = function (event) {
  72745. _this.db = request.result;
  72746. successCallback();
  72747. };
  72748. // Initialization of the DB. Creating Scenes & Textures stores
  72749. request.onupgradeneeded = function (event) {
  72750. _this.db = (event.target).result;
  72751. if (_this.db) {
  72752. try {
  72753. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72754. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72755. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72756. }
  72757. catch (ex) {
  72758. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72759. handleError();
  72760. }
  72761. }
  72762. };
  72763. }
  72764. // DB has already been created and opened
  72765. else {
  72766. if (successCallback)
  72767. successCallback();
  72768. }
  72769. }
  72770. };
  72771. /**
  72772. * Loads an image from the database
  72773. * @param url defines the url to load from
  72774. * @param image defines the target DOM image
  72775. */
  72776. Database.prototype.loadImageFromDB = function (url, image) {
  72777. var _this = this;
  72778. var completeURL = Database._ReturnFullUrlLocation(url);
  72779. var saveAndLoadImage = function () {
  72780. if (!_this.hasReachedQuota && _this.db !== null) {
  72781. // the texture is not yet in the DB, let's try to save it
  72782. _this._saveImageIntoDBAsync(completeURL, image);
  72783. }
  72784. // If the texture is not in the DB and we've reached the DB quota limit
  72785. // let's load it directly from the web
  72786. else {
  72787. image.src = url;
  72788. }
  72789. };
  72790. if (!this.mustUpdateRessources) {
  72791. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72792. }
  72793. // First time we're download the images or update requested in the manifest file by a version change
  72794. else {
  72795. saveAndLoadImage();
  72796. }
  72797. };
  72798. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72799. if (this.isSupported && this.db !== null) {
  72800. var texture;
  72801. var transaction = this.db.transaction(["textures"]);
  72802. transaction.onabort = function (event) {
  72803. image.src = url;
  72804. };
  72805. transaction.oncomplete = function (event) {
  72806. var blobTextureURL;
  72807. if (texture) {
  72808. var URL = window.URL || window.webkitURL;
  72809. blobTextureURL = URL.createObjectURL(texture.data);
  72810. image.onerror = function () {
  72811. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72812. image.src = url;
  72813. };
  72814. image.src = blobTextureURL;
  72815. }
  72816. else {
  72817. notInDBCallback();
  72818. }
  72819. };
  72820. var getRequest = transaction.objectStore("textures").get(url);
  72821. getRequest.onsuccess = function (event) {
  72822. texture = (event.target).result;
  72823. };
  72824. getRequest.onerror = function (event) {
  72825. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72826. image.src = url;
  72827. };
  72828. }
  72829. else {
  72830. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72831. image.src = url;
  72832. }
  72833. };
  72834. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72835. var _this = this;
  72836. if (this.isSupported) {
  72837. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72838. var generateBlobUrl = function () {
  72839. var blobTextureURL;
  72840. if (blob) {
  72841. var URL = window.URL || window.webkitURL;
  72842. try {
  72843. blobTextureURL = URL.createObjectURL(blob);
  72844. }
  72845. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72846. catch (ex) {
  72847. blobTextureURL = URL.createObjectURL(blob);
  72848. }
  72849. }
  72850. if (blobTextureURL) {
  72851. image.src = blobTextureURL;
  72852. }
  72853. };
  72854. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72855. var xhr = new XMLHttpRequest(), blob;
  72856. xhr.open("GET", url, true);
  72857. xhr.responseType = "blob";
  72858. xhr.addEventListener("load", function () {
  72859. if (xhr.status === 200 && _this.db) {
  72860. // Blob as response (XHR2)
  72861. blob = xhr.response;
  72862. var transaction = _this.db.transaction(["textures"], "readwrite");
  72863. // the transaction could abort because of a QuotaExceededError error
  72864. transaction.onabort = function (event) {
  72865. try {
  72866. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72867. var srcElement = (event.srcElement || event.target);
  72868. var error = srcElement.error;
  72869. if (error && error.name === "QuotaExceededError") {
  72870. _this.hasReachedQuota = true;
  72871. }
  72872. }
  72873. catch (ex) { }
  72874. generateBlobUrl();
  72875. };
  72876. transaction.oncomplete = function (event) {
  72877. generateBlobUrl();
  72878. };
  72879. var newTexture = { textureUrl: url, data: blob };
  72880. try {
  72881. // Put the blob into the dabase
  72882. var addRequest = transaction.objectStore("textures").put(newTexture);
  72883. addRequest.onsuccess = function (event) {
  72884. };
  72885. addRequest.onerror = function (event) {
  72886. generateBlobUrl();
  72887. };
  72888. }
  72889. catch (ex) {
  72890. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72891. if (ex.code === 25) {
  72892. Database.IsUASupportingBlobStorage = false;
  72893. }
  72894. image.src = url;
  72895. }
  72896. }
  72897. else {
  72898. image.src = url;
  72899. }
  72900. }, false);
  72901. xhr.addEventListener("error", function (event) {
  72902. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72903. image.src = url;
  72904. }, false);
  72905. xhr.send();
  72906. }
  72907. else {
  72908. image.src = url;
  72909. }
  72910. }
  72911. else {
  72912. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72913. image.src = url;
  72914. }
  72915. };
  72916. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72917. var _this = this;
  72918. var updateVersion = function () {
  72919. // the version is not yet in the DB or we need to update it
  72920. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72921. };
  72922. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72923. };
  72924. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72925. var _this = this;
  72926. if (this.isSupported && this.db) {
  72927. var version;
  72928. try {
  72929. var transaction = this.db.transaction(["versions"]);
  72930. transaction.oncomplete = function (event) {
  72931. if (version) {
  72932. // If the version in the JSON file is different from the version in DB
  72933. if (_this.manifestVersionFound !== version.data) {
  72934. _this.mustUpdateRessources = true;
  72935. updateInDBCallback();
  72936. }
  72937. else {
  72938. callback(version.data);
  72939. }
  72940. }
  72941. // version was not found in DB
  72942. else {
  72943. _this.mustUpdateRessources = true;
  72944. updateInDBCallback();
  72945. }
  72946. };
  72947. transaction.onabort = function (event) {
  72948. callback(-1);
  72949. };
  72950. var getRequest = transaction.objectStore("versions").get(url);
  72951. getRequest.onsuccess = function (event) {
  72952. version = (event.target).result;
  72953. };
  72954. getRequest.onerror = function (event) {
  72955. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72956. callback(-1);
  72957. };
  72958. }
  72959. catch (ex) {
  72960. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72961. callback(-1);
  72962. }
  72963. }
  72964. else {
  72965. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72966. callback(-1);
  72967. }
  72968. };
  72969. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72970. var _this = this;
  72971. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72972. try {
  72973. // Open a transaction to the database
  72974. var transaction = this.db.transaction(["versions"], "readwrite");
  72975. // the transaction could abort because of a QuotaExceededError error
  72976. transaction.onabort = function (event) {
  72977. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72978. var error = event.srcElement['error'];
  72979. if (error && error.name === "QuotaExceededError") {
  72980. _this.hasReachedQuota = true;
  72981. }
  72982. }
  72983. catch (ex) { }
  72984. callback(-1);
  72985. };
  72986. transaction.oncomplete = function (event) {
  72987. callback(_this.manifestVersionFound);
  72988. };
  72989. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72990. // Put the scene into the database
  72991. var addRequest = transaction.objectStore("versions").put(newVersion);
  72992. addRequest.onsuccess = function (event) {
  72993. };
  72994. addRequest.onerror = function (event) {
  72995. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72996. };
  72997. }
  72998. catch (ex) {
  72999. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73000. callback(-1);
  73001. }
  73002. }
  73003. else {
  73004. callback(-1);
  73005. }
  73006. };
  73007. /**
  73008. * Loads a file from database
  73009. * @param url defines the URL to load from
  73010. * @param sceneLoaded defines a callback to call on success
  73011. * @param progressCallBack defines a callback to call when progress changed
  73012. * @param errorCallback defines a callback to call on error
  73013. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73014. */
  73015. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73016. var _this = this;
  73017. var completeUrl = Database._ReturnFullUrlLocation(url);
  73018. var saveAndLoadFile = function () {
  73019. // the scene is not yet in the DB, let's try to save it
  73020. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73021. };
  73022. this._checkVersionFromDB(completeUrl, function (version) {
  73023. if (version !== -1) {
  73024. if (!_this.mustUpdateRessources) {
  73025. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73026. }
  73027. else {
  73028. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73029. }
  73030. }
  73031. else {
  73032. if (errorCallback) {
  73033. errorCallback();
  73034. }
  73035. }
  73036. });
  73037. };
  73038. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73039. if (this.isSupported && this.db) {
  73040. var targetStore;
  73041. if (url.indexOf(".babylon") !== -1) {
  73042. targetStore = "scenes";
  73043. }
  73044. else {
  73045. targetStore = "textures";
  73046. }
  73047. var file;
  73048. var transaction = this.db.transaction([targetStore]);
  73049. transaction.oncomplete = function (event) {
  73050. if (file) {
  73051. callback(file.data);
  73052. }
  73053. // file was not found in DB
  73054. else {
  73055. notInDBCallback();
  73056. }
  73057. };
  73058. transaction.onabort = function (event) {
  73059. notInDBCallback();
  73060. };
  73061. var getRequest = transaction.objectStore(targetStore).get(url);
  73062. getRequest.onsuccess = function (event) {
  73063. file = (event.target).result;
  73064. };
  73065. getRequest.onerror = function (event) {
  73066. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73067. notInDBCallback();
  73068. };
  73069. }
  73070. else {
  73071. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73072. callback();
  73073. }
  73074. };
  73075. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73076. var _this = this;
  73077. if (this.isSupported) {
  73078. var targetStore;
  73079. if (url.indexOf(".babylon") !== -1) {
  73080. targetStore = "scenes";
  73081. }
  73082. else {
  73083. targetStore = "textures";
  73084. }
  73085. // Create XHR
  73086. var xhr = new XMLHttpRequest();
  73087. var fileData;
  73088. xhr.open("GET", url + "?" + Date.now(), true);
  73089. if (useArrayBuffer) {
  73090. xhr.responseType = "arraybuffer";
  73091. }
  73092. if (progressCallback) {
  73093. xhr.onprogress = progressCallback;
  73094. }
  73095. xhr.addEventListener("load", function () {
  73096. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73097. // Blob as response (XHR2)
  73098. //fileData = xhr.responseText;
  73099. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73100. if (!_this.hasReachedQuota && _this.db) {
  73101. // Open a transaction to the database
  73102. var transaction = _this.db.transaction([targetStore], "readwrite");
  73103. // the transaction could abort because of a QuotaExceededError error
  73104. transaction.onabort = function (event) {
  73105. try {
  73106. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73107. var error = event.srcElement['error'];
  73108. if (error && error.name === "QuotaExceededError") {
  73109. _this.hasReachedQuota = true;
  73110. }
  73111. }
  73112. catch (ex) { }
  73113. callback(fileData);
  73114. };
  73115. transaction.oncomplete = function (event) {
  73116. callback(fileData);
  73117. };
  73118. var newFile;
  73119. if (targetStore === "scenes") {
  73120. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73121. }
  73122. else {
  73123. newFile = { textureUrl: url, data: fileData };
  73124. }
  73125. try {
  73126. // Put the scene into the database
  73127. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73128. addRequest.onsuccess = function (event) {
  73129. };
  73130. addRequest.onerror = function (event) {
  73131. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73132. };
  73133. }
  73134. catch (ex) {
  73135. callback(fileData);
  73136. }
  73137. }
  73138. else {
  73139. callback(fileData);
  73140. }
  73141. }
  73142. else {
  73143. if (xhr.status >= 400 && errorCallback) {
  73144. errorCallback(xhr);
  73145. }
  73146. else {
  73147. callback();
  73148. }
  73149. }
  73150. }, false);
  73151. xhr.addEventListener("error", function (event) {
  73152. BABYLON.Tools.Error("error on XHR request.");
  73153. callback();
  73154. }, false);
  73155. xhr.send();
  73156. }
  73157. else {
  73158. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73159. callback();
  73160. }
  73161. };
  73162. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73163. Database.IsUASupportingBlobStorage = true;
  73164. /** Gets a boolean indicating if Database storate is enabled */
  73165. Database.IDBStorageEnabled = true;
  73166. Database._ParseURL = function (url) {
  73167. var a = document.createElement('a');
  73168. a.href = url;
  73169. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73170. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73171. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73172. return absLocation;
  73173. };
  73174. Database._ReturnFullUrlLocation = function (url) {
  73175. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73176. return (Database._ParseURL(window.location.href) + url);
  73177. }
  73178. else {
  73179. return url;
  73180. }
  73181. };
  73182. return Database;
  73183. }());
  73184. BABYLON.Database = Database;
  73185. })(BABYLON || (BABYLON = {}));
  73186. //# sourceMappingURL=babylon.database.js.map
  73187. var BABYLON;
  73188. (function (BABYLON) {
  73189. var FresnelParameters = /** @class */ (function () {
  73190. function FresnelParameters() {
  73191. this._isEnabled = true;
  73192. this.leftColor = BABYLON.Color3.White();
  73193. this.rightColor = BABYLON.Color3.Black();
  73194. this.bias = 0;
  73195. this.power = 1;
  73196. }
  73197. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73198. get: function () {
  73199. return this._isEnabled;
  73200. },
  73201. set: function (value) {
  73202. if (this._isEnabled === value) {
  73203. return;
  73204. }
  73205. this._isEnabled = value;
  73206. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73207. },
  73208. enumerable: true,
  73209. configurable: true
  73210. });
  73211. FresnelParameters.prototype.clone = function () {
  73212. var newFresnelParameters = new FresnelParameters();
  73213. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73214. return newFresnelParameters;
  73215. };
  73216. FresnelParameters.prototype.serialize = function () {
  73217. var serializationObject = {};
  73218. serializationObject.isEnabled = this.isEnabled;
  73219. serializationObject.leftColor = this.leftColor.asArray();
  73220. serializationObject.rightColor = this.rightColor.asArray();
  73221. serializationObject.bias = this.bias;
  73222. serializationObject.power = this.power;
  73223. return serializationObject;
  73224. };
  73225. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73226. var fresnelParameters = new FresnelParameters();
  73227. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73228. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73229. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73230. fresnelParameters.bias = parsedFresnelParameters.bias;
  73231. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73232. return fresnelParameters;
  73233. };
  73234. return FresnelParameters;
  73235. }());
  73236. BABYLON.FresnelParameters = FresnelParameters;
  73237. })(BABYLON || (BABYLON = {}));
  73238. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73239. var BABYLON;
  73240. (function (BABYLON) {
  73241. var MultiMaterial = /** @class */ (function (_super) {
  73242. __extends(MultiMaterial, _super);
  73243. function MultiMaterial(name, scene) {
  73244. var _this = _super.call(this, name, scene, true) || this;
  73245. scene.multiMaterials.push(_this);
  73246. _this.subMaterials = new Array();
  73247. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73248. return _this;
  73249. }
  73250. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73251. get: function () {
  73252. return this._subMaterials;
  73253. },
  73254. set: function (value) {
  73255. this._subMaterials = value;
  73256. this._hookArray(value);
  73257. },
  73258. enumerable: true,
  73259. configurable: true
  73260. });
  73261. MultiMaterial.prototype._hookArray = function (array) {
  73262. var _this = this;
  73263. var oldPush = array.push;
  73264. array.push = function () {
  73265. var items = [];
  73266. for (var _i = 0; _i < arguments.length; _i++) {
  73267. items[_i] = arguments[_i];
  73268. }
  73269. var result = oldPush.apply(array, items);
  73270. _this._markAllSubMeshesAsTexturesDirty();
  73271. return result;
  73272. };
  73273. var oldSplice = array.splice;
  73274. array.splice = function (index, deleteCount) {
  73275. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73276. _this._markAllSubMeshesAsTexturesDirty();
  73277. return deleted;
  73278. };
  73279. };
  73280. // Properties
  73281. MultiMaterial.prototype.getSubMaterial = function (index) {
  73282. if (index < 0 || index >= this.subMaterials.length) {
  73283. return this.getScene().defaultMaterial;
  73284. }
  73285. return this.subMaterials[index];
  73286. };
  73287. MultiMaterial.prototype.getActiveTextures = function () {
  73288. var _a;
  73289. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  73290. if (subMaterial) {
  73291. return subMaterial.getActiveTextures();
  73292. }
  73293. else {
  73294. return [];
  73295. }
  73296. }));
  73297. };
  73298. // Methods
  73299. MultiMaterial.prototype.getClassName = function () {
  73300. return "MultiMaterial";
  73301. };
  73302. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73303. for (var index = 0; index < this.subMaterials.length; index++) {
  73304. var subMaterial = this.subMaterials[index];
  73305. if (subMaterial) {
  73306. if (subMaterial.storeEffectOnSubMeshes) {
  73307. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  73308. return false;
  73309. }
  73310. continue;
  73311. }
  73312. if (!subMaterial.isReady(mesh)) {
  73313. return false;
  73314. }
  73315. }
  73316. }
  73317. return true;
  73318. };
  73319. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  73320. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  73321. for (var index = 0; index < this.subMaterials.length; index++) {
  73322. var subMaterial = null;
  73323. var current = this.subMaterials[index];
  73324. if (cloneChildren && current) {
  73325. subMaterial = current.clone(name + "-" + current.name);
  73326. }
  73327. else {
  73328. subMaterial = this.subMaterials[index];
  73329. }
  73330. newMultiMaterial.subMaterials.push(subMaterial);
  73331. }
  73332. return newMultiMaterial;
  73333. };
  73334. MultiMaterial.prototype.serialize = function () {
  73335. var serializationObject = {};
  73336. serializationObject.name = this.name;
  73337. serializationObject.id = this.id;
  73338. if (BABYLON.Tags) {
  73339. serializationObject.tags = BABYLON.Tags.GetTags(this);
  73340. }
  73341. serializationObject.materials = [];
  73342. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  73343. var subMat = this.subMaterials[matIndex];
  73344. if (subMat) {
  73345. serializationObject.materials.push(subMat.id);
  73346. }
  73347. else {
  73348. serializationObject.materials.push(null);
  73349. }
  73350. }
  73351. return serializationObject;
  73352. };
  73353. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  73354. var scene = this.getScene();
  73355. if (!scene) {
  73356. return;
  73357. }
  73358. var index = scene.multiMaterials.indexOf(this);
  73359. if (index >= 0) {
  73360. scene.multiMaterials.splice(index, 1);
  73361. }
  73362. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  73363. };
  73364. return MultiMaterial;
  73365. }(BABYLON.Material));
  73366. BABYLON.MultiMaterial = MultiMaterial;
  73367. })(BABYLON || (BABYLON = {}));
  73368. //# sourceMappingURL=babylon.multiMaterial.js.map
  73369. var BABYLON;
  73370. (function (BABYLON) {
  73371. var FreeCameraTouchInput = /** @class */ (function () {
  73372. function FreeCameraTouchInput() {
  73373. this._offsetX = null;
  73374. this._offsetY = null;
  73375. this._pointerPressed = new Array();
  73376. this.touchAngularSensibility = 200000.0;
  73377. this.touchMoveSensibility = 250.0;
  73378. }
  73379. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73380. var _this = this;
  73381. var previousPosition = null;
  73382. if (this._pointerInput === undefined) {
  73383. this._onLostFocus = function (evt) {
  73384. _this._offsetX = null;
  73385. _this._offsetY = null;
  73386. };
  73387. this._pointerInput = function (p, s) {
  73388. var evt = p.event;
  73389. if (evt.pointerType === "mouse") {
  73390. return;
  73391. }
  73392. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73393. if (!noPreventDefault) {
  73394. evt.preventDefault();
  73395. }
  73396. _this._pointerPressed.push(evt.pointerId);
  73397. if (_this._pointerPressed.length !== 1) {
  73398. return;
  73399. }
  73400. previousPosition = {
  73401. x: evt.clientX,
  73402. y: evt.clientY
  73403. };
  73404. }
  73405. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73406. if (!noPreventDefault) {
  73407. evt.preventDefault();
  73408. }
  73409. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73410. if (index === -1) {
  73411. return;
  73412. }
  73413. _this._pointerPressed.splice(index, 1);
  73414. if (index != 0) {
  73415. return;
  73416. }
  73417. previousPosition = null;
  73418. _this._offsetX = null;
  73419. _this._offsetY = null;
  73420. }
  73421. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73422. if (!noPreventDefault) {
  73423. evt.preventDefault();
  73424. }
  73425. if (!previousPosition) {
  73426. return;
  73427. }
  73428. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73429. if (index != 0) {
  73430. return;
  73431. }
  73432. _this._offsetX = evt.clientX - previousPosition.x;
  73433. _this._offsetY = -(evt.clientY - previousPosition.y);
  73434. }
  73435. };
  73436. }
  73437. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73438. if (this._onLostFocus) {
  73439. element.addEventListener("blur", this._onLostFocus);
  73440. }
  73441. };
  73442. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73443. if (this._pointerInput && element) {
  73444. if (this._observer) {
  73445. this.camera.getScene().onPointerObservable.remove(this._observer);
  73446. this._observer = null;
  73447. }
  73448. if (this._onLostFocus) {
  73449. element.removeEventListener("blur", this._onLostFocus);
  73450. this._onLostFocus = null;
  73451. }
  73452. this._pointerPressed = [];
  73453. this._offsetX = null;
  73454. this._offsetY = null;
  73455. }
  73456. };
  73457. FreeCameraTouchInput.prototype.checkInputs = function () {
  73458. if (this._offsetX && this._offsetY) {
  73459. var camera = this.camera;
  73460. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73461. if (this._pointerPressed.length > 1) {
  73462. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73463. }
  73464. else {
  73465. var speed = camera._computeLocalCameraSpeed();
  73466. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73467. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73468. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73469. }
  73470. }
  73471. };
  73472. FreeCameraTouchInput.prototype.getClassName = function () {
  73473. return "FreeCameraTouchInput";
  73474. };
  73475. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73476. return "touch";
  73477. };
  73478. __decorate([
  73479. BABYLON.serialize()
  73480. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73481. __decorate([
  73482. BABYLON.serialize()
  73483. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73484. return FreeCameraTouchInput;
  73485. }());
  73486. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73487. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73488. })(BABYLON || (BABYLON = {}));
  73489. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73490. var BABYLON;
  73491. (function (BABYLON) {
  73492. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73493. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73494. });
  73495. // We're mainly based on the logic defined into the FreeCamera code
  73496. var TouchCamera = /** @class */ (function (_super) {
  73497. __extends(TouchCamera, _super);
  73498. //-- end properties for backward compatibility for inputs
  73499. function TouchCamera(name, position, scene) {
  73500. var _this = _super.call(this, name, position, scene) || this;
  73501. _this.inputs.addTouch();
  73502. _this._setupInputs();
  73503. return _this;
  73504. }
  73505. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73506. //-- Begin properties for backward compatibility for inputs
  73507. get: function () {
  73508. var touch = this.inputs.attached["touch"];
  73509. if (touch)
  73510. return touch.touchAngularSensibility;
  73511. return 0;
  73512. },
  73513. set: function (value) {
  73514. var touch = this.inputs.attached["touch"];
  73515. if (touch)
  73516. touch.touchAngularSensibility = value;
  73517. },
  73518. enumerable: true,
  73519. configurable: true
  73520. });
  73521. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  73522. get: function () {
  73523. var touch = this.inputs.attached["touch"];
  73524. if (touch)
  73525. return touch.touchMoveSensibility;
  73526. return 0;
  73527. },
  73528. set: function (value) {
  73529. var touch = this.inputs.attached["touch"];
  73530. if (touch)
  73531. touch.touchMoveSensibility = value;
  73532. },
  73533. enumerable: true,
  73534. configurable: true
  73535. });
  73536. TouchCamera.prototype.getClassName = function () {
  73537. return "TouchCamera";
  73538. };
  73539. /** @hidden */
  73540. TouchCamera.prototype._setupInputs = function () {
  73541. var mouse = this.inputs.attached["mouse"];
  73542. if (mouse) {
  73543. mouse.touchEnabled = false;
  73544. }
  73545. };
  73546. return TouchCamera;
  73547. }(BABYLON.FreeCamera));
  73548. BABYLON.TouchCamera = TouchCamera;
  73549. })(BABYLON || (BABYLON = {}));
  73550. //# sourceMappingURL=babylon.touchCamera.js.map
  73551. var BABYLON;
  73552. (function (BABYLON) {
  73553. var ProceduralTexture = /** @class */ (function (_super) {
  73554. __extends(ProceduralTexture, _super);
  73555. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73556. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73557. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73558. if (isCube === void 0) { isCube = false; }
  73559. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73560. _this.isCube = isCube;
  73561. _this.isEnabled = true;
  73562. _this._currentRefreshId = -1;
  73563. _this._refreshRate = 1;
  73564. _this._vertexBuffers = {};
  73565. _this._uniforms = new Array();
  73566. _this._samplers = new Array();
  73567. /** @hidden */
  73568. _this._textures = {};
  73569. _this._floats = {};
  73570. _this._ints = {};
  73571. _this._floatsArrays = {};
  73572. _this._colors3 = {};
  73573. _this._colors4 = {};
  73574. _this._vectors2 = {};
  73575. _this._vectors3 = {};
  73576. _this._matrices = {};
  73577. _this._fallbackTextureUsed = false;
  73578. _this._cachedDefines = "";
  73579. scene = _this.getScene();
  73580. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  73581. if (!component) {
  73582. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  73583. scene._addComponent(component);
  73584. }
  73585. scene.proceduralTextures.push(_this);
  73586. _this._engine = scene.getEngine();
  73587. _this.name = name;
  73588. _this.isRenderTarget = true;
  73589. _this._size = size;
  73590. _this._generateMipMaps = generateMipMaps;
  73591. _this.setFragment(fragment);
  73592. _this._fallbackTexture = fallbackTexture;
  73593. if (isCube) {
  73594. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  73595. _this.setFloat("face", 0);
  73596. }
  73597. else {
  73598. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  73599. }
  73600. // VBO
  73601. var vertices = [];
  73602. vertices.push(1, 1);
  73603. vertices.push(-1, 1);
  73604. vertices.push(-1, -1);
  73605. vertices.push(1, -1);
  73606. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73607. _this._createIndexBuffer();
  73608. return _this;
  73609. }
  73610. ProceduralTexture.prototype._createIndexBuffer = function () {
  73611. var engine = this._engine;
  73612. // Indices
  73613. var indices = [];
  73614. indices.push(0);
  73615. indices.push(1);
  73616. indices.push(2);
  73617. indices.push(0);
  73618. indices.push(2);
  73619. indices.push(3);
  73620. this._indexBuffer = engine.createIndexBuffer(indices);
  73621. };
  73622. /** @hidden */
  73623. ProceduralTexture.prototype._rebuild = function () {
  73624. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73625. if (vb) {
  73626. vb._rebuild();
  73627. }
  73628. this._createIndexBuffer();
  73629. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73630. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73631. }
  73632. };
  73633. ProceduralTexture.prototype.reset = function () {
  73634. if (this._effect === undefined) {
  73635. return;
  73636. }
  73637. var engine = this._engine;
  73638. engine._releaseEffect(this._effect);
  73639. };
  73640. ProceduralTexture.prototype._getDefines = function () {
  73641. return "";
  73642. };
  73643. ProceduralTexture.prototype.isReady = function () {
  73644. var _this = this;
  73645. var engine = this._engine;
  73646. var shaders;
  73647. if (!this._fragment) {
  73648. return false;
  73649. }
  73650. if (this._fallbackTextureUsed) {
  73651. return true;
  73652. }
  73653. var defines = this._getDefines();
  73654. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  73655. return true;
  73656. }
  73657. if (this._fragment.fragmentElement !== undefined) {
  73658. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73659. }
  73660. else {
  73661. shaders = { vertex: "procedural", fragment: this._fragment };
  73662. }
  73663. this._cachedDefines = defines;
  73664. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  73665. _this.releaseInternalTexture();
  73666. if (_this._fallbackTexture) {
  73667. _this._texture = _this._fallbackTexture._texture;
  73668. if (_this._texture) {
  73669. _this._texture.incrementReferences();
  73670. }
  73671. }
  73672. _this._fallbackTextureUsed = true;
  73673. });
  73674. return this._effect.isReady();
  73675. };
  73676. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73677. this._currentRefreshId = -1;
  73678. };
  73679. ProceduralTexture.prototype.setFragment = function (fragment) {
  73680. this._fragment = fragment;
  73681. };
  73682. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73683. get: function () {
  73684. return this._refreshRate;
  73685. },
  73686. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73687. set: function (value) {
  73688. this._refreshRate = value;
  73689. this.resetRefreshCounter();
  73690. },
  73691. enumerable: true,
  73692. configurable: true
  73693. });
  73694. /** @hidden */
  73695. ProceduralTexture.prototype._shouldRender = function () {
  73696. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73697. return false;
  73698. }
  73699. if (this._fallbackTextureUsed) {
  73700. return false;
  73701. }
  73702. if (this._currentRefreshId === -1) { // At least render once
  73703. this._currentRefreshId = 1;
  73704. return true;
  73705. }
  73706. if (this.refreshRate === this._currentRefreshId) {
  73707. this._currentRefreshId = 1;
  73708. return true;
  73709. }
  73710. this._currentRefreshId++;
  73711. return false;
  73712. };
  73713. ProceduralTexture.prototype.getRenderSize = function () {
  73714. return this._size;
  73715. };
  73716. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73717. if (this._fallbackTextureUsed) {
  73718. return;
  73719. }
  73720. this.releaseInternalTexture();
  73721. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73722. // Update properties
  73723. this._size = size;
  73724. this._generateMipMaps = generateMipMaps;
  73725. };
  73726. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73727. if (this._uniforms.indexOf(uniformName) === -1) {
  73728. this._uniforms.push(uniformName);
  73729. }
  73730. };
  73731. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73732. if (this._samplers.indexOf(name) === -1) {
  73733. this._samplers.push(name);
  73734. }
  73735. this._textures[name] = texture;
  73736. return this;
  73737. };
  73738. ProceduralTexture.prototype.setFloat = function (name, value) {
  73739. this._checkUniform(name);
  73740. this._floats[name] = value;
  73741. return this;
  73742. };
  73743. /**
  73744. * Set the value of an uniform to an integer value
  73745. * @param name defines the name of the uniform
  73746. * @param value defines the value to set
  73747. * @returns the current procedural texture
  73748. */
  73749. ProceduralTexture.prototype.setInt = function (name, value) {
  73750. this._checkUniform(name);
  73751. this._ints[name] = value;
  73752. return this;
  73753. };
  73754. ProceduralTexture.prototype.setFloats = function (name, value) {
  73755. this._checkUniform(name);
  73756. this._floatsArrays[name] = value;
  73757. return this;
  73758. };
  73759. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73760. this._checkUniform(name);
  73761. this._colors3[name] = value;
  73762. return this;
  73763. };
  73764. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73765. this._checkUniform(name);
  73766. this._colors4[name] = value;
  73767. return this;
  73768. };
  73769. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73770. this._checkUniform(name);
  73771. this._vectors2[name] = value;
  73772. return this;
  73773. };
  73774. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73775. this._checkUniform(name);
  73776. this._vectors3[name] = value;
  73777. return this;
  73778. };
  73779. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73780. this._checkUniform(name);
  73781. this._matrices[name] = value;
  73782. return this;
  73783. };
  73784. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73785. var scene = this.getScene();
  73786. if (!scene) {
  73787. return;
  73788. }
  73789. var engine = this._engine;
  73790. // Render
  73791. engine.enableEffect(this._effect);
  73792. engine.setState(false);
  73793. // Texture
  73794. for (var name in this._textures) {
  73795. this._effect.setTexture(name, this._textures[name]);
  73796. }
  73797. // Float
  73798. for (name in this._ints) {
  73799. this._effect.setInt(name, this._ints[name]);
  73800. }
  73801. // Float
  73802. for (name in this._floats) {
  73803. this._effect.setFloat(name, this._floats[name]);
  73804. }
  73805. // Floats
  73806. for (name in this._floatsArrays) {
  73807. this._effect.setArray(name, this._floatsArrays[name]);
  73808. }
  73809. // Color3
  73810. for (name in this._colors3) {
  73811. this._effect.setColor3(name, this._colors3[name]);
  73812. }
  73813. // Color4
  73814. for (name in this._colors4) {
  73815. var color = this._colors4[name];
  73816. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73817. }
  73818. // Vector2
  73819. for (name in this._vectors2) {
  73820. this._effect.setVector2(name, this._vectors2[name]);
  73821. }
  73822. // Vector3
  73823. for (name in this._vectors3) {
  73824. this._effect.setVector3(name, this._vectors3[name]);
  73825. }
  73826. // Matrix
  73827. for (name in this._matrices) {
  73828. this._effect.setMatrix(name, this._matrices[name]);
  73829. }
  73830. if (!this._texture) {
  73831. return;
  73832. }
  73833. if (this.isCube) {
  73834. for (var face = 0; face < 6; face++) {
  73835. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73836. // VBOs
  73837. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73838. this._effect.setFloat("face", face);
  73839. // Clear
  73840. engine.clear(scene.clearColor, true, true, true);
  73841. // Draw order
  73842. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73843. // Mipmaps
  73844. if (face === 5) {
  73845. engine.generateMipMapsForCubemap(this._texture);
  73846. }
  73847. }
  73848. }
  73849. else {
  73850. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73851. // VBOs
  73852. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73853. // Clear
  73854. engine.clear(scene.clearColor, true, true, true);
  73855. // Draw order
  73856. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73857. }
  73858. // Unbind
  73859. engine.unBindFramebuffer(this._texture, this.isCube);
  73860. if (this.onGenerated) {
  73861. this.onGenerated();
  73862. }
  73863. };
  73864. ProceduralTexture.prototype.clone = function () {
  73865. var textureSize = this.getSize();
  73866. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73867. // Base texture
  73868. newTexture.hasAlpha = this.hasAlpha;
  73869. newTexture.level = this.level;
  73870. // RenderTarget Texture
  73871. newTexture.coordinatesMode = this.coordinatesMode;
  73872. return newTexture;
  73873. };
  73874. ProceduralTexture.prototype.dispose = function () {
  73875. var scene = this.getScene();
  73876. if (!scene) {
  73877. return;
  73878. }
  73879. var index = scene.proceduralTextures.indexOf(this);
  73880. if (index >= 0) {
  73881. scene.proceduralTextures.splice(index, 1);
  73882. }
  73883. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73884. if (vertexBuffer) {
  73885. vertexBuffer.dispose();
  73886. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73887. }
  73888. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73889. this._indexBuffer = null;
  73890. }
  73891. _super.prototype.dispose.call(this);
  73892. };
  73893. __decorate([
  73894. BABYLON.serialize()
  73895. ], ProceduralTexture.prototype, "_size", void 0);
  73896. __decorate([
  73897. BABYLON.serialize()
  73898. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73899. __decorate([
  73900. BABYLON.serialize()
  73901. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73902. __decorate([
  73903. BABYLON.serialize()
  73904. ], ProceduralTexture.prototype, "refreshRate", null);
  73905. return ProceduralTexture;
  73906. }(BABYLON.Texture));
  73907. BABYLON.ProceduralTexture = ProceduralTexture;
  73908. })(BABYLON || (BABYLON = {}));
  73909. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73910. var BABYLON;
  73911. (function (BABYLON) {
  73912. /**
  73913. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  73914. * in a given scene.
  73915. */
  73916. var ProceduralTextureSceneComponent = /** @class */ (function () {
  73917. /**
  73918. * Creates a new instance of the component for the given scene
  73919. * @param scene Defines the scene to register the component in
  73920. */
  73921. function ProceduralTextureSceneComponent(scene) {
  73922. /**
  73923. * The component name helpfull to identify the component in the list of scene components.
  73924. */
  73925. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  73926. this.scene = scene;
  73927. this.scene.proceduralTextures = new Array();
  73928. scene.layers = new Array();
  73929. }
  73930. /**
  73931. * Registers the component in a given scene
  73932. */
  73933. ProceduralTextureSceneComponent.prototype.register = function () {
  73934. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  73935. };
  73936. /**
  73937. * Rebuilds the elements related to this component in case of
  73938. * context lost for instance.
  73939. */
  73940. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  73941. // Nothing to do here.
  73942. };
  73943. /**
  73944. * Disposes the component and the associated ressources.
  73945. */
  73946. ProceduralTextureSceneComponent.prototype.dispose = function () {
  73947. // Nothing to do here.
  73948. };
  73949. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  73950. if (this.scene.proceduralTexturesEnabled) {
  73951. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  73952. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  73953. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  73954. if (proceduralTexture._shouldRender()) {
  73955. proceduralTexture.render();
  73956. }
  73957. }
  73958. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  73959. }
  73960. };
  73961. return ProceduralTextureSceneComponent;
  73962. }());
  73963. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  73964. })(BABYLON || (BABYLON = {}));
  73965. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  73966. var BABYLON;
  73967. (function (BABYLON) {
  73968. var CustomProceduralTexture = /** @class */ (function (_super) {
  73969. __extends(CustomProceduralTexture, _super);
  73970. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73971. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73972. _this._animate = true;
  73973. _this._time = 0;
  73974. _this._texturePath = texturePath;
  73975. //Try to load json
  73976. _this.loadJson(texturePath);
  73977. _this.refreshRate = 1;
  73978. return _this;
  73979. }
  73980. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73981. var _this = this;
  73982. var noConfigFile = function () {
  73983. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73984. try {
  73985. _this.setFragment(_this._texturePath);
  73986. }
  73987. catch (ex) {
  73988. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73989. }
  73990. };
  73991. var configFileUrl = jsonUrl + "/config.json";
  73992. var xhr = new XMLHttpRequest();
  73993. xhr.open("GET", configFileUrl, true);
  73994. xhr.addEventListener("load", function () {
  73995. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73996. try {
  73997. _this._config = JSON.parse(xhr.response);
  73998. _this.updateShaderUniforms();
  73999. _this.updateTextures();
  74000. _this.setFragment(_this._texturePath + "/custom");
  74001. _this._animate = _this._config.animate;
  74002. _this.refreshRate = _this._config.refreshrate;
  74003. }
  74004. catch (ex) {
  74005. noConfigFile();
  74006. }
  74007. }
  74008. else {
  74009. noConfigFile();
  74010. }
  74011. }, false);
  74012. xhr.addEventListener("error", function () {
  74013. noConfigFile();
  74014. }, false);
  74015. try {
  74016. xhr.send();
  74017. }
  74018. catch (ex) {
  74019. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74020. }
  74021. };
  74022. CustomProceduralTexture.prototype.isReady = function () {
  74023. if (!_super.prototype.isReady.call(this)) {
  74024. return false;
  74025. }
  74026. for (var name in this._textures) {
  74027. var texture = this._textures[name];
  74028. if (!texture.isReady()) {
  74029. return false;
  74030. }
  74031. }
  74032. return true;
  74033. };
  74034. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74035. var scene = this.getScene();
  74036. if (this._animate && scene) {
  74037. this._time += scene.getAnimationRatio() * 0.03;
  74038. this.updateShaderUniforms();
  74039. }
  74040. _super.prototype.render.call(this, useCameraPostProcess);
  74041. };
  74042. CustomProceduralTexture.prototype.updateTextures = function () {
  74043. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74044. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74045. }
  74046. };
  74047. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74048. if (this._config) {
  74049. for (var j = 0; j < this._config.uniforms.length; j++) {
  74050. var uniform = this._config.uniforms[j];
  74051. switch (uniform.type) {
  74052. case "float":
  74053. this.setFloat(uniform.name, uniform.value);
  74054. break;
  74055. case "color3":
  74056. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74057. break;
  74058. case "color4":
  74059. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74060. break;
  74061. case "vector2":
  74062. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74063. break;
  74064. case "vector3":
  74065. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74066. break;
  74067. }
  74068. }
  74069. }
  74070. this.setFloat("time", this._time);
  74071. };
  74072. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74073. get: function () {
  74074. return this._animate;
  74075. },
  74076. set: function (value) {
  74077. this._animate = value;
  74078. },
  74079. enumerable: true,
  74080. configurable: true
  74081. });
  74082. return CustomProceduralTexture;
  74083. }(BABYLON.ProceduralTexture));
  74084. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74085. })(BABYLON || (BABYLON = {}));
  74086. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74087. var BABYLON;
  74088. (function (BABYLON) {
  74089. var FreeCameraGamepadInput = /** @class */ (function () {
  74090. function FreeCameraGamepadInput() {
  74091. this.gamepadAngularSensibility = 200;
  74092. this.gamepadMoveSensibility = 40;
  74093. // private members
  74094. this._cameraTransform = BABYLON.Matrix.Identity();
  74095. this._deltaTransform = BABYLON.Vector3.Zero();
  74096. this._vector3 = BABYLON.Vector3.Zero();
  74097. this._vector2 = BABYLON.Vector2.Zero();
  74098. }
  74099. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74100. var _this = this;
  74101. var manager = this.camera.getScene().gamepadManager;
  74102. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74103. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74104. // prioritize XBOX gamepads.
  74105. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74106. _this.gamepad = gamepad;
  74107. }
  74108. }
  74109. });
  74110. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74111. if (_this.gamepad === gamepad) {
  74112. _this.gamepad = null;
  74113. }
  74114. });
  74115. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74116. };
  74117. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74118. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74119. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74120. this.gamepad = null;
  74121. };
  74122. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74123. if (this.gamepad && this.gamepad.leftStick) {
  74124. var camera = this.camera;
  74125. var LSValues = this.gamepad.leftStick;
  74126. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74127. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74128. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74129. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74130. var RSValues = this.gamepad.rightStick;
  74131. if (RSValues) {
  74132. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74133. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74134. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74135. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74136. }
  74137. else {
  74138. RSValues = { x: 0, y: 0 };
  74139. }
  74140. if (!camera.rotationQuaternion) {
  74141. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74142. }
  74143. else {
  74144. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74145. }
  74146. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74147. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74148. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74149. camera.cameraDirection.addInPlace(this._deltaTransform);
  74150. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74151. camera.cameraRotation.addInPlace(this._vector2);
  74152. }
  74153. };
  74154. FreeCameraGamepadInput.prototype.getClassName = function () {
  74155. return "FreeCameraGamepadInput";
  74156. };
  74157. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74158. return "gamepad";
  74159. };
  74160. __decorate([
  74161. BABYLON.serialize()
  74162. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74163. __decorate([
  74164. BABYLON.serialize()
  74165. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74166. return FreeCameraGamepadInput;
  74167. }());
  74168. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74169. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74170. })(BABYLON || (BABYLON = {}));
  74171. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74172. var BABYLON;
  74173. (function (BABYLON) {
  74174. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74175. function ArcRotateCameraGamepadInput() {
  74176. this.gamepadRotationSensibility = 80;
  74177. this.gamepadMoveSensibility = 40;
  74178. }
  74179. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74180. var _this = this;
  74181. var manager = this.camera.getScene().gamepadManager;
  74182. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74183. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74184. // prioritize XBOX gamepads.
  74185. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74186. _this.gamepad = gamepad;
  74187. }
  74188. }
  74189. });
  74190. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74191. if (_this.gamepad === gamepad) {
  74192. _this.gamepad = null;
  74193. }
  74194. });
  74195. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74196. };
  74197. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74198. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74199. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74200. this.gamepad = null;
  74201. };
  74202. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74203. if (this.gamepad) {
  74204. var camera = this.camera;
  74205. var RSValues = this.gamepad.rightStick;
  74206. if (RSValues) {
  74207. if (RSValues.x != 0) {
  74208. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74209. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74210. camera.inertialAlphaOffset += normalizedRX;
  74211. }
  74212. }
  74213. if (RSValues.y != 0) {
  74214. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74215. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74216. camera.inertialBetaOffset += normalizedRY;
  74217. }
  74218. }
  74219. }
  74220. var LSValues = this.gamepad.leftStick;
  74221. if (LSValues && LSValues.y != 0) {
  74222. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74223. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74224. this.camera.inertialRadiusOffset -= normalizedLY;
  74225. }
  74226. }
  74227. }
  74228. };
  74229. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74230. return "ArcRotateCameraGamepadInput";
  74231. };
  74232. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74233. return "gamepad";
  74234. };
  74235. __decorate([
  74236. BABYLON.serialize()
  74237. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  74238. __decorate([
  74239. BABYLON.serialize()
  74240. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74241. return ArcRotateCameraGamepadInput;
  74242. }());
  74243. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  74244. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  74245. })(BABYLON || (BABYLON = {}));
  74246. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  74247. var BABYLON;
  74248. (function (BABYLON) {
  74249. var GamepadManager = /** @class */ (function () {
  74250. function GamepadManager(_scene) {
  74251. var _this = this;
  74252. this._scene = _scene;
  74253. this._babylonGamepads = [];
  74254. this._oneGamepadConnected = false;
  74255. /** @hidden */
  74256. this._isMonitoring = false;
  74257. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  74258. if (!BABYLON.Tools.IsWindowObjectExist()) {
  74259. this._gamepadEventSupported = false;
  74260. }
  74261. else {
  74262. this._gamepadEventSupported = 'GamepadEvent' in window;
  74263. this._gamepadSupport = (navigator.getGamepads ||
  74264. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  74265. }
  74266. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  74267. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  74268. for (var i in _this._babylonGamepads) {
  74269. var gamepad = _this._babylonGamepads[i];
  74270. if (gamepad && gamepad._isConnected) {
  74271. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  74272. }
  74273. }
  74274. });
  74275. this._onGamepadConnectedEvent = function (evt) {
  74276. var gamepad = evt.gamepad;
  74277. if (gamepad.index in _this._babylonGamepads) {
  74278. if (_this._babylonGamepads[gamepad.index].isConnected) {
  74279. return;
  74280. }
  74281. }
  74282. var newGamepad;
  74283. if (_this._babylonGamepads[gamepad.index]) {
  74284. newGamepad = _this._babylonGamepads[gamepad.index];
  74285. newGamepad.browserGamepad = gamepad;
  74286. newGamepad._isConnected = true;
  74287. }
  74288. else {
  74289. newGamepad = _this._addNewGamepad(gamepad);
  74290. }
  74291. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74292. _this._startMonitoringGamepads();
  74293. };
  74294. this._onGamepadDisconnectedEvent = function (evt) {
  74295. var gamepad = evt.gamepad;
  74296. // Remove the gamepad from the list of gamepads to monitor.
  74297. for (var i in _this._babylonGamepads) {
  74298. if (_this._babylonGamepads[i].index === gamepad.index) {
  74299. var disconnectedGamepad = _this._babylonGamepads[i];
  74300. disconnectedGamepad._isConnected = false;
  74301. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  74302. break;
  74303. }
  74304. }
  74305. };
  74306. if (this._gamepadSupport) {
  74307. //first add already-connected gamepads
  74308. this._updateGamepadObjects();
  74309. if (this._babylonGamepads.length) {
  74310. this._startMonitoringGamepads();
  74311. }
  74312. // Checking if the gamepad connected event is supported (like in Firefox)
  74313. if (this._gamepadEventSupported) {
  74314. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  74315. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  74316. }
  74317. else {
  74318. this._startMonitoringGamepads();
  74319. }
  74320. }
  74321. }
  74322. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  74323. get: function () {
  74324. return this._babylonGamepads;
  74325. },
  74326. enumerable: true,
  74327. configurable: true
  74328. });
  74329. GamepadManager.prototype.getGamepadByType = function (type) {
  74330. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  74331. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  74332. var gamepad = _a[_i];
  74333. if (gamepad && gamepad.type === type) {
  74334. return gamepad;
  74335. }
  74336. }
  74337. return null;
  74338. };
  74339. GamepadManager.prototype.dispose = function () {
  74340. if (this._gamepadEventSupported) {
  74341. if (this._onGamepadConnectedEvent) {
  74342. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  74343. }
  74344. if (this._onGamepadDisconnectedEvent) {
  74345. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  74346. }
  74347. this._onGamepadConnectedEvent = null;
  74348. this._onGamepadDisconnectedEvent = null;
  74349. }
  74350. this._babylonGamepads.forEach(function (gamepad) {
  74351. gamepad.dispose();
  74352. });
  74353. this.onGamepadConnectedObservable.clear();
  74354. this.onGamepadDisconnectedObservable.clear();
  74355. this._oneGamepadConnected = false;
  74356. this._stopMonitoringGamepads();
  74357. this._babylonGamepads = [];
  74358. };
  74359. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  74360. if (!this._oneGamepadConnected) {
  74361. this._oneGamepadConnected = true;
  74362. }
  74363. var newGamepad;
  74364. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  74365. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  74366. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  74367. }
  74368. // if pose is supported, use the (WebVR) pose enabled controller
  74369. else if (gamepad.pose) {
  74370. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  74371. }
  74372. else {
  74373. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  74374. }
  74375. this._babylonGamepads[newGamepad.index] = newGamepad;
  74376. return newGamepad;
  74377. };
  74378. GamepadManager.prototype._startMonitoringGamepads = function () {
  74379. if (!this._isMonitoring) {
  74380. this._isMonitoring = true;
  74381. //back-comp
  74382. if (!this._scene) {
  74383. this._checkGamepadsStatus();
  74384. }
  74385. }
  74386. };
  74387. GamepadManager.prototype._stopMonitoringGamepads = function () {
  74388. this._isMonitoring = false;
  74389. };
  74390. /** @hidden */
  74391. GamepadManager.prototype._checkGamepadsStatus = function () {
  74392. var _this = this;
  74393. // Hack to be compatible Chrome
  74394. this._updateGamepadObjects();
  74395. for (var i in this._babylonGamepads) {
  74396. var gamepad = this._babylonGamepads[i];
  74397. if (!gamepad || !gamepad.isConnected) {
  74398. continue;
  74399. }
  74400. gamepad.update();
  74401. }
  74402. if (this._isMonitoring && !this._scene) {
  74403. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  74404. }
  74405. };
  74406. // This function is called only on Chrome, which does not properly support
  74407. // connection/disconnection events and forces you to recopy again the gamepad object
  74408. GamepadManager.prototype._updateGamepadObjects = function () {
  74409. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  74410. for (var i = 0; i < gamepads.length; i++) {
  74411. var gamepad = gamepads[i];
  74412. if (gamepad) {
  74413. if (!this._babylonGamepads[gamepad.index]) {
  74414. var newGamepad = this._addNewGamepad(gamepad);
  74415. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74416. }
  74417. else {
  74418. // Forced to copy again this object for Chrome for unknown reason
  74419. this._babylonGamepads[i].browserGamepad = gamepad;
  74420. if (!this._babylonGamepads[i].isConnected) {
  74421. this._babylonGamepads[i]._isConnected = true;
  74422. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  74423. }
  74424. }
  74425. }
  74426. }
  74427. };
  74428. return GamepadManager;
  74429. }());
  74430. BABYLON.GamepadManager = GamepadManager;
  74431. })(BABYLON || (BABYLON = {}));
  74432. //# sourceMappingURL=babylon.gamepadManager.js.map
  74433. var BABYLON;
  74434. (function (BABYLON) {
  74435. var StickValues = /** @class */ (function () {
  74436. function StickValues(x, y) {
  74437. this.x = x;
  74438. this.y = y;
  74439. }
  74440. return StickValues;
  74441. }());
  74442. BABYLON.StickValues = StickValues;
  74443. var Gamepad = /** @class */ (function () {
  74444. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74445. if (leftStickX === void 0) { leftStickX = 0; }
  74446. if (leftStickY === void 0) { leftStickY = 1; }
  74447. if (rightStickX === void 0) { rightStickX = 2; }
  74448. if (rightStickY === void 0) { rightStickY = 3; }
  74449. this.id = id;
  74450. this.index = index;
  74451. this.browserGamepad = browserGamepad;
  74452. this._leftStick = { x: 0, y: 0 };
  74453. this._rightStick = { x: 0, y: 0 };
  74454. /** @hidden */
  74455. this._isConnected = true;
  74456. this._invertLeftStickY = false;
  74457. this.type = Gamepad.GAMEPAD;
  74458. this._leftStickAxisX = leftStickX;
  74459. this._leftStickAxisY = leftStickY;
  74460. this._rightStickAxisX = rightStickX;
  74461. this._rightStickAxisY = rightStickY;
  74462. if (this.browserGamepad.axes.length >= 2) {
  74463. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74464. }
  74465. if (this.browserGamepad.axes.length >= 4) {
  74466. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74467. }
  74468. }
  74469. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74470. get: function () {
  74471. return this._isConnected;
  74472. },
  74473. enumerable: true,
  74474. configurable: true
  74475. });
  74476. Gamepad.prototype.onleftstickchanged = function (callback) {
  74477. this._onleftstickchanged = callback;
  74478. };
  74479. Gamepad.prototype.onrightstickchanged = function (callback) {
  74480. this._onrightstickchanged = callback;
  74481. };
  74482. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74483. get: function () {
  74484. return this._leftStick;
  74485. },
  74486. set: function (newValues) {
  74487. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74488. this._onleftstickchanged(newValues);
  74489. }
  74490. this._leftStick = newValues;
  74491. },
  74492. enumerable: true,
  74493. configurable: true
  74494. });
  74495. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74496. get: function () {
  74497. return this._rightStick;
  74498. },
  74499. set: function (newValues) {
  74500. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74501. this._onrightstickchanged(newValues);
  74502. }
  74503. this._rightStick = newValues;
  74504. },
  74505. enumerable: true,
  74506. configurable: true
  74507. });
  74508. Gamepad.prototype.update = function () {
  74509. if (this._leftStick) {
  74510. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74511. if (this._invertLeftStickY) {
  74512. this.leftStick.y *= -1;
  74513. }
  74514. }
  74515. if (this._rightStick) {
  74516. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74517. }
  74518. };
  74519. Gamepad.prototype.dispose = function () {
  74520. };
  74521. Gamepad.GAMEPAD = 0;
  74522. Gamepad.GENERIC = 1;
  74523. Gamepad.XBOX = 2;
  74524. Gamepad.POSE_ENABLED = 3;
  74525. return Gamepad;
  74526. }());
  74527. BABYLON.Gamepad = Gamepad;
  74528. var GenericPad = /** @class */ (function (_super) {
  74529. __extends(GenericPad, _super);
  74530. function GenericPad(id, index, browserGamepad) {
  74531. var _this = _super.call(this, id, index, browserGamepad) || this;
  74532. _this.onButtonDownObservable = new BABYLON.Observable();
  74533. _this.onButtonUpObservable = new BABYLON.Observable();
  74534. _this.type = Gamepad.GENERIC;
  74535. _this._buttons = new Array(browserGamepad.buttons.length);
  74536. return _this;
  74537. }
  74538. GenericPad.prototype.onbuttondown = function (callback) {
  74539. this._onbuttondown = callback;
  74540. };
  74541. GenericPad.prototype.onbuttonup = function (callback) {
  74542. this._onbuttonup = callback;
  74543. };
  74544. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  74545. if (newValue !== currentValue) {
  74546. if (newValue === 1) {
  74547. if (this._onbuttondown) {
  74548. this._onbuttondown(buttonIndex);
  74549. }
  74550. this.onButtonDownObservable.notifyObservers(buttonIndex);
  74551. }
  74552. if (newValue === 0) {
  74553. if (this._onbuttonup) {
  74554. this._onbuttonup(buttonIndex);
  74555. }
  74556. this.onButtonUpObservable.notifyObservers(buttonIndex);
  74557. }
  74558. }
  74559. return newValue;
  74560. };
  74561. GenericPad.prototype.update = function () {
  74562. _super.prototype.update.call(this);
  74563. for (var index = 0; index < this._buttons.length; index++) {
  74564. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  74565. }
  74566. };
  74567. GenericPad.prototype.dispose = function () {
  74568. _super.prototype.dispose.call(this);
  74569. this.onButtonDownObservable.clear();
  74570. this.onButtonUpObservable.clear();
  74571. };
  74572. return GenericPad;
  74573. }(Gamepad));
  74574. BABYLON.GenericPad = GenericPad;
  74575. })(BABYLON || (BABYLON = {}));
  74576. //# sourceMappingURL=babylon.gamepad.js.map
  74577. var BABYLON;
  74578. (function (BABYLON) {
  74579. /**
  74580. * Defines supported buttons for XBox360 compatible gamepads
  74581. */
  74582. var Xbox360Button;
  74583. (function (Xbox360Button) {
  74584. /** A */
  74585. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  74586. /** B */
  74587. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  74588. /** X */
  74589. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  74590. /** Y */
  74591. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  74592. /** Start */
  74593. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  74594. /** Back */
  74595. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  74596. /** Left button */
  74597. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  74598. /** Right button */
  74599. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  74600. /** Left stick */
  74601. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  74602. /** Right stick */
  74603. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  74604. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  74605. /** Defines values for XBox360 DPad */
  74606. var Xbox360Dpad;
  74607. (function (Xbox360Dpad) {
  74608. /** Up */
  74609. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  74610. /** Down */
  74611. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  74612. /** Left */
  74613. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  74614. /** Right */
  74615. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  74616. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  74617. /**
  74618. * Defines a XBox360 gamepad
  74619. */
  74620. var Xbox360Pad = /** @class */ (function (_super) {
  74621. __extends(Xbox360Pad, _super);
  74622. /**
  74623. * Creates a new XBox360 gamepad object
  74624. * @param id defines the id of this gamepad
  74625. * @param index defines its index
  74626. * @param gamepad defines the internal HTML gamepad object
  74627. * @param xboxOne defines if it is a XBox One gamepad
  74628. */
  74629. function Xbox360Pad(id, index, gamepad, xboxOne) {
  74630. if (xboxOne === void 0) { xboxOne = false; }
  74631. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  74632. _this._leftTrigger = 0;
  74633. _this._rightTrigger = 0;
  74634. /** Observable raised when a button is pressed */
  74635. _this.onButtonDownObservable = new BABYLON.Observable();
  74636. /** Observable raised when a button is released */
  74637. _this.onButtonUpObservable = new BABYLON.Observable();
  74638. /** Observable raised when a pad is pressed */
  74639. _this.onPadDownObservable = new BABYLON.Observable();
  74640. /** Observable raised when a pad is released */
  74641. _this.onPadUpObservable = new BABYLON.Observable();
  74642. _this._buttonA = 0;
  74643. _this._buttonB = 0;
  74644. _this._buttonX = 0;
  74645. _this._buttonY = 0;
  74646. _this._buttonBack = 0;
  74647. _this._buttonStart = 0;
  74648. _this._buttonLB = 0;
  74649. _this._buttonRB = 0;
  74650. _this._buttonLeftStick = 0;
  74651. _this._buttonRightStick = 0;
  74652. _this._dPadUp = 0;
  74653. _this._dPadDown = 0;
  74654. _this._dPadLeft = 0;
  74655. _this._dPadRight = 0;
  74656. _this._isXboxOnePad = false;
  74657. _this.type = BABYLON.Gamepad.XBOX;
  74658. _this._isXboxOnePad = xboxOne;
  74659. return _this;
  74660. }
  74661. /**
  74662. * Defines the callback to call when left trigger is pressed
  74663. * @param callback defines the callback to use
  74664. */
  74665. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  74666. this._onlefttriggerchanged = callback;
  74667. };
  74668. /**
  74669. * Defines the callback to call when right trigger is pressed
  74670. * @param callback defines the callback to use
  74671. */
  74672. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  74673. this._onrighttriggerchanged = callback;
  74674. };
  74675. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  74676. /**
  74677. * Gets or sets left trigger value
  74678. */
  74679. get: function () {
  74680. return this._leftTrigger;
  74681. },
  74682. set: function (newValue) {
  74683. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  74684. this._onlefttriggerchanged(newValue);
  74685. }
  74686. this._leftTrigger = newValue;
  74687. },
  74688. enumerable: true,
  74689. configurable: true
  74690. });
  74691. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74692. /**
  74693. * Gets or sets right trigger value
  74694. */
  74695. get: function () {
  74696. return this._rightTrigger;
  74697. },
  74698. set: function (newValue) {
  74699. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74700. this._onrighttriggerchanged(newValue);
  74701. }
  74702. this._rightTrigger = newValue;
  74703. },
  74704. enumerable: true,
  74705. configurable: true
  74706. });
  74707. /**
  74708. * Defines the callback to call when a button is pressed
  74709. * @param callback defines the callback to use
  74710. */
  74711. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74712. this._onbuttondown = callback;
  74713. };
  74714. /**
  74715. * Defines the callback to call when a button is released
  74716. * @param callback defines the callback to use
  74717. */
  74718. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74719. this._onbuttonup = callback;
  74720. };
  74721. /**
  74722. * Defines the callback to call when a pad is pressed
  74723. * @param callback defines the callback to use
  74724. */
  74725. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74726. this._ondpaddown = callback;
  74727. };
  74728. /**
  74729. * Defines the callback to call when a pad is released
  74730. * @param callback defines the callback to use
  74731. */
  74732. Xbox360Pad.prototype.ondpadup = function (callback) {
  74733. this._ondpadup = callback;
  74734. };
  74735. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74736. if (newValue !== currentValue) {
  74737. if (newValue === 1) {
  74738. if (this._onbuttondown) {
  74739. this._onbuttondown(buttonType);
  74740. }
  74741. this.onButtonDownObservable.notifyObservers(buttonType);
  74742. }
  74743. if (newValue === 0) {
  74744. if (this._onbuttonup) {
  74745. this._onbuttonup(buttonType);
  74746. }
  74747. this.onButtonUpObservable.notifyObservers(buttonType);
  74748. }
  74749. }
  74750. return newValue;
  74751. };
  74752. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74753. if (newValue !== currentValue) {
  74754. if (newValue === 1) {
  74755. if (this._ondpaddown) {
  74756. this._ondpaddown(buttonType);
  74757. }
  74758. this.onPadDownObservable.notifyObservers(buttonType);
  74759. }
  74760. if (newValue === 0) {
  74761. if (this._ondpadup) {
  74762. this._ondpadup(buttonType);
  74763. }
  74764. this.onPadUpObservable.notifyObservers(buttonType);
  74765. }
  74766. }
  74767. return newValue;
  74768. };
  74769. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74770. /** Gets or sets value of A button */
  74771. get: function () {
  74772. return this._buttonA;
  74773. },
  74774. set: function (value) {
  74775. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74776. },
  74777. enumerable: true,
  74778. configurable: true
  74779. });
  74780. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74781. /** Gets or sets value of B button */
  74782. get: function () {
  74783. return this._buttonB;
  74784. },
  74785. set: function (value) {
  74786. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74787. },
  74788. enumerable: true,
  74789. configurable: true
  74790. });
  74791. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74792. /** Gets or sets value of X button */
  74793. get: function () {
  74794. return this._buttonX;
  74795. },
  74796. set: function (value) {
  74797. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74798. },
  74799. enumerable: true,
  74800. configurable: true
  74801. });
  74802. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74803. /** Gets or sets value of Y button */
  74804. get: function () {
  74805. return this._buttonY;
  74806. },
  74807. set: function (value) {
  74808. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74809. },
  74810. enumerable: true,
  74811. configurable: true
  74812. });
  74813. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74814. /** Gets or sets value of Start button */
  74815. get: function () {
  74816. return this._buttonStart;
  74817. },
  74818. set: function (value) {
  74819. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74820. },
  74821. enumerable: true,
  74822. configurable: true
  74823. });
  74824. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74825. /** Gets or sets value of Back button */
  74826. get: function () {
  74827. return this._buttonBack;
  74828. },
  74829. set: function (value) {
  74830. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74831. },
  74832. enumerable: true,
  74833. configurable: true
  74834. });
  74835. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74836. /** Gets or sets value of Left button */
  74837. get: function () {
  74838. return this._buttonLB;
  74839. },
  74840. set: function (value) {
  74841. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74842. },
  74843. enumerable: true,
  74844. configurable: true
  74845. });
  74846. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74847. /** Gets or sets value of Right button */
  74848. get: function () {
  74849. return this._buttonRB;
  74850. },
  74851. set: function (value) {
  74852. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74853. },
  74854. enumerable: true,
  74855. configurable: true
  74856. });
  74857. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74858. /** Gets or sets value of left stick */
  74859. get: function () {
  74860. return this._buttonLeftStick;
  74861. },
  74862. set: function (value) {
  74863. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74864. },
  74865. enumerable: true,
  74866. configurable: true
  74867. });
  74868. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74869. /** Gets or sets value of right stick */
  74870. get: function () {
  74871. return this._buttonRightStick;
  74872. },
  74873. set: function (value) {
  74874. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74880. /** Gets or sets value of DPad up */
  74881. get: function () {
  74882. return this._dPadUp;
  74883. },
  74884. set: function (value) {
  74885. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74886. },
  74887. enumerable: true,
  74888. configurable: true
  74889. });
  74890. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74891. /** Gets or sets value of DPad down */
  74892. get: function () {
  74893. return this._dPadDown;
  74894. },
  74895. set: function (value) {
  74896. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74897. },
  74898. enumerable: true,
  74899. configurable: true
  74900. });
  74901. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74902. /** Gets or sets value of DPad left */
  74903. get: function () {
  74904. return this._dPadLeft;
  74905. },
  74906. set: function (value) {
  74907. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74908. },
  74909. enumerable: true,
  74910. configurable: true
  74911. });
  74912. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74913. /** Gets or sets value of DPad right */
  74914. get: function () {
  74915. return this._dPadRight;
  74916. },
  74917. set: function (value) {
  74918. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74919. },
  74920. enumerable: true,
  74921. configurable: true
  74922. });
  74923. /**
  74924. * Force the gamepad to synchronize with device values
  74925. */
  74926. Xbox360Pad.prototype.update = function () {
  74927. _super.prototype.update.call(this);
  74928. if (this._isXboxOnePad) {
  74929. this.buttonA = this.browserGamepad.buttons[0].value;
  74930. this.buttonB = this.browserGamepad.buttons[1].value;
  74931. this.buttonX = this.browserGamepad.buttons[2].value;
  74932. this.buttonY = this.browserGamepad.buttons[3].value;
  74933. this.buttonLB = this.browserGamepad.buttons[4].value;
  74934. this.buttonRB = this.browserGamepad.buttons[5].value;
  74935. this.leftTrigger = this.browserGamepad.axes[2];
  74936. this.rightTrigger = this.browserGamepad.axes[5];
  74937. this.buttonBack = this.browserGamepad.buttons[9].value;
  74938. this.buttonStart = this.browserGamepad.buttons[8].value;
  74939. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74940. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74941. this.dPadUp = this.browserGamepad.buttons[11].value;
  74942. this.dPadDown = this.browserGamepad.buttons[12].value;
  74943. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74944. this.dPadRight = this.browserGamepad.buttons[14].value;
  74945. }
  74946. else {
  74947. this.buttonA = this.browserGamepad.buttons[0].value;
  74948. this.buttonB = this.browserGamepad.buttons[1].value;
  74949. this.buttonX = this.browserGamepad.buttons[2].value;
  74950. this.buttonY = this.browserGamepad.buttons[3].value;
  74951. this.buttonLB = this.browserGamepad.buttons[4].value;
  74952. this.buttonRB = this.browserGamepad.buttons[5].value;
  74953. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74954. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74955. this.buttonBack = this.browserGamepad.buttons[8].value;
  74956. this.buttonStart = this.browserGamepad.buttons[9].value;
  74957. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74958. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74959. this.dPadUp = this.browserGamepad.buttons[12].value;
  74960. this.dPadDown = this.browserGamepad.buttons[13].value;
  74961. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74962. this.dPadRight = this.browserGamepad.buttons[15].value;
  74963. }
  74964. };
  74965. Xbox360Pad.prototype.dispose = function () {
  74966. _super.prototype.dispose.call(this);
  74967. this.onButtonDownObservable.clear();
  74968. this.onButtonUpObservable.clear();
  74969. this.onPadDownObservable.clear();
  74970. this.onPadUpObservable.clear();
  74971. };
  74972. return Xbox360Pad;
  74973. }(BABYLON.Gamepad));
  74974. BABYLON.Xbox360Pad = Xbox360Pad;
  74975. })(BABYLON || (BABYLON = {}));
  74976. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74977. var BABYLON;
  74978. (function (BABYLON) {
  74979. /**
  74980. * Defines the types of pose enabled controllers that are supported
  74981. */
  74982. var PoseEnabledControllerType;
  74983. (function (PoseEnabledControllerType) {
  74984. /**
  74985. * HTC Vive
  74986. */
  74987. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74988. /**
  74989. * Oculus Rift
  74990. */
  74991. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74992. /**
  74993. * Windows mixed reality
  74994. */
  74995. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74996. /**
  74997. * Samsung gear VR
  74998. */
  74999. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75000. /**
  75001. * Google Daydream
  75002. */
  75003. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75004. /**
  75005. * Generic
  75006. */
  75007. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75008. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75009. /**
  75010. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75011. */
  75012. var PoseEnabledControllerHelper = /** @class */ (function () {
  75013. function PoseEnabledControllerHelper() {
  75014. }
  75015. /**
  75016. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75017. * @param vrGamepad the gamepad to initialized
  75018. * @returns a vr controller of the type the gamepad identified as
  75019. */
  75020. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75021. // Oculus Touch
  75022. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75023. return new BABYLON.OculusTouchController(vrGamepad);
  75024. }
  75025. // Windows Mixed Reality controllers
  75026. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75027. return new BABYLON.WindowsMotionController(vrGamepad);
  75028. }
  75029. // HTC Vive
  75030. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75031. return new BABYLON.ViveController(vrGamepad);
  75032. }
  75033. // Samsung/Oculus Gear VR or Oculus Go
  75034. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75035. return new BABYLON.GearVRController(vrGamepad);
  75036. }
  75037. // Google Daydream
  75038. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75039. return new BABYLON.DaydreamController(vrGamepad);
  75040. }
  75041. // Generic
  75042. else {
  75043. return new BABYLON.GenericController(vrGamepad);
  75044. }
  75045. };
  75046. return PoseEnabledControllerHelper;
  75047. }());
  75048. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75049. /**
  75050. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75051. */
  75052. var PoseEnabledController = /** @class */ (function (_super) {
  75053. __extends(PoseEnabledController, _super);
  75054. /**
  75055. * Creates a new PoseEnabledController from a gamepad
  75056. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75057. */
  75058. function PoseEnabledController(browserGamepad) {
  75059. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75060. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75061. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75062. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75063. /**
  75064. * The device position in babylon space
  75065. */
  75066. _this.devicePosition = BABYLON.Vector3.Zero();
  75067. /**
  75068. * The device rotation in babylon space
  75069. */
  75070. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75071. /**
  75072. * The scale factor of the device in babylon space
  75073. */
  75074. _this.deviceScaleFactor = 1;
  75075. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75076. /**
  75077. * Internal, matrix used to convert room space to babylon space
  75078. * @hidden
  75079. */
  75080. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75081. /**
  75082. * Node to be used when casting a ray from the controller
  75083. * @hidden
  75084. */
  75085. _this._pointingPoseNode = null;
  75086. _this._workingMatrix = BABYLON.Matrix.Identity();
  75087. /**
  75088. * @hidden
  75089. */
  75090. _this._meshAttachedObservable = new BABYLON.Observable();
  75091. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75092. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75093. _this.position = BABYLON.Vector3.Zero();
  75094. _this.rotationQuaternion = new BABYLON.Quaternion();
  75095. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75096. _this._calculatedRotation = new BABYLON.Quaternion();
  75097. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75098. return _this;
  75099. }
  75100. /**
  75101. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75102. */
  75103. PoseEnabledController.prototype.update = function () {
  75104. _super.prototype.update.call(this);
  75105. this._updatePoseAndMesh();
  75106. };
  75107. /**
  75108. * Updates only the pose device and mesh without doing any button event checking
  75109. */
  75110. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75111. var pose = this.browserGamepad.pose;
  75112. this.updateFromDevice(pose);
  75113. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75114. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75115. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75116. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75117. if (this._mesh) {
  75118. this._mesh.position.copyFrom(this.devicePosition);
  75119. if (this._mesh.rotationQuaternion) {
  75120. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75121. }
  75122. }
  75123. };
  75124. /**
  75125. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75126. * @param poseData raw pose fromthe device
  75127. */
  75128. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75129. if (poseData) {
  75130. this.rawPose = poseData;
  75131. if (poseData.position) {
  75132. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75133. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75134. this._deviceRoomPosition.z *= -1;
  75135. }
  75136. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75137. this._calculatedPosition.addInPlace(this.position);
  75138. }
  75139. var pose = this.rawPose;
  75140. if (poseData.orientation && pose.orientation) {
  75141. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75142. if (this._mesh) {
  75143. if (this._mesh.getScene().useRightHandedSystem) {
  75144. this._deviceRoomRotationQuaternion.z *= -1;
  75145. this._deviceRoomRotationQuaternion.w *= -1;
  75146. }
  75147. else {
  75148. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75149. }
  75150. }
  75151. // if the camera is set, rotate to the camera's rotation
  75152. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75153. }
  75154. }
  75155. };
  75156. /**
  75157. * Attaches a mesh to the controller
  75158. * @param mesh the mesh to be attached
  75159. */
  75160. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75161. if (this._mesh) {
  75162. this._mesh.parent = null;
  75163. }
  75164. this._mesh = mesh;
  75165. if (this._poseControlledCamera) {
  75166. this._mesh.parent = this._poseControlledCamera;
  75167. }
  75168. if (!this._mesh.rotationQuaternion) {
  75169. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75170. }
  75171. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  75172. this._updatePoseAndMesh();
  75173. if (this._pointingPoseNode) {
  75174. var parents = [];
  75175. var obj = this._pointingPoseNode;
  75176. while (obj.parent) {
  75177. parents.push(obj.parent);
  75178. obj = obj.parent;
  75179. }
  75180. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75181. }
  75182. this._meshAttachedObservable.notifyObservers(mesh);
  75183. };
  75184. /**
  75185. * Attaches the controllers mesh to a camera
  75186. * @param camera the camera the mesh should be attached to
  75187. */
  75188. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75189. this._poseControlledCamera = camera;
  75190. if (this._mesh) {
  75191. this._mesh.parent = this._poseControlledCamera;
  75192. }
  75193. };
  75194. /**
  75195. * Disposes of the controller
  75196. */
  75197. PoseEnabledController.prototype.dispose = function () {
  75198. if (this._mesh) {
  75199. this._mesh.dispose();
  75200. }
  75201. this._mesh = null;
  75202. _super.prototype.dispose.call(this);
  75203. };
  75204. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75205. /**
  75206. * The mesh that is attached to the controller
  75207. */
  75208. get: function () {
  75209. return this._mesh;
  75210. },
  75211. enumerable: true,
  75212. configurable: true
  75213. });
  75214. /**
  75215. * Gets the ray of the controller in the direction the controller is pointing
  75216. * @param length the length the resulting ray should be
  75217. * @returns a ray in the direction the controller is pointing
  75218. */
  75219. PoseEnabledController.prototype.getForwardRay = function (length) {
  75220. if (length === void 0) { length = 100; }
  75221. if (!this.mesh) {
  75222. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75223. }
  75224. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75225. var origin = m.getTranslation();
  75226. var forward = new BABYLON.Vector3(0, 0, -1);
  75227. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75228. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75229. return new BABYLON.Ray(origin, direction, length);
  75230. };
  75231. /**
  75232. * Name of the child mesh that can be used to cast a ray from the controller
  75233. */
  75234. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75235. return PoseEnabledController;
  75236. }(BABYLON.Gamepad));
  75237. BABYLON.PoseEnabledController = PoseEnabledController;
  75238. })(BABYLON || (BABYLON = {}));
  75239. //# sourceMappingURL=babylon.poseEnabledController.js.map
  75240. var BABYLON;
  75241. (function (BABYLON) {
  75242. /**
  75243. * Defines the WebVRController object that represents controllers tracked in 3D space
  75244. */
  75245. var WebVRController = /** @class */ (function (_super) {
  75246. __extends(WebVRController, _super);
  75247. /**
  75248. * Creates a new WebVRController from a gamepad
  75249. * @param vrGamepad the gamepad that the WebVRController should be created from
  75250. */
  75251. function WebVRController(vrGamepad) {
  75252. var _this = _super.call(this, vrGamepad) || this;
  75253. // Observables
  75254. /**
  75255. * Fired when the trigger state has changed
  75256. */
  75257. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  75258. /**
  75259. * Fired when the main button state has changed
  75260. */
  75261. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  75262. /**
  75263. * Fired when the secondary button state has changed
  75264. */
  75265. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  75266. /**
  75267. * Fired when the pad state has changed
  75268. */
  75269. _this.onPadStateChangedObservable = new BABYLON.Observable();
  75270. /**
  75271. * Fired when controllers stick values have changed
  75272. */
  75273. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  75274. /**
  75275. * X and Y axis corrisponding to the controllers joystick
  75276. */
  75277. _this.pad = { x: 0, y: 0 };
  75278. // avoid GC, store state in a tmp object
  75279. _this._changes = {
  75280. pressChanged: false,
  75281. touchChanged: false,
  75282. valueChanged: false,
  75283. changed: false
  75284. };
  75285. _this._buttons = new Array(vrGamepad.buttons.length);
  75286. _this.hand = vrGamepad.hand;
  75287. return _this;
  75288. }
  75289. /**
  75290. * Fired when a controller button's state has changed
  75291. * @param callback the callback containing the button that was modified
  75292. */
  75293. WebVRController.prototype.onButtonStateChange = function (callback) {
  75294. this._onButtonStateChange = callback;
  75295. };
  75296. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  75297. /**
  75298. * The default controller model for the controller
  75299. */
  75300. get: function () {
  75301. return this._defaultModel;
  75302. },
  75303. enumerable: true,
  75304. configurable: true
  75305. });
  75306. /**
  75307. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  75308. */
  75309. WebVRController.prototype.update = function () {
  75310. _super.prototype.update.call(this);
  75311. for (var index = 0; index < this._buttons.length; index++) {
  75312. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  75313. }
  75314. ;
  75315. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  75316. this.pad.x = this.leftStick.x;
  75317. this.pad.y = this.leftStick.y;
  75318. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  75319. }
  75320. };
  75321. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  75322. if (!newState) {
  75323. newState = {
  75324. pressed: false,
  75325. touched: false,
  75326. value: 0
  75327. };
  75328. }
  75329. if (!currentState) {
  75330. this._buttons[buttonIndex] = {
  75331. pressed: newState.pressed,
  75332. touched: newState.touched,
  75333. value: newState.value
  75334. };
  75335. return;
  75336. }
  75337. this._checkChanges(newState, currentState);
  75338. if (this._changes.changed) {
  75339. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  75340. this._handleButtonChange(buttonIndex, newState, this._changes);
  75341. }
  75342. this._buttons[buttonIndex].pressed = newState.pressed;
  75343. this._buttons[buttonIndex].touched = newState.touched;
  75344. // oculus triggers are never 0, thou not touched.
  75345. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  75346. };
  75347. WebVRController.prototype._checkChanges = function (newState, currentState) {
  75348. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  75349. this._changes.touchChanged = newState.touched !== currentState.touched;
  75350. this._changes.valueChanged = newState.value !== currentState.value;
  75351. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  75352. return this._changes;
  75353. };
  75354. /**
  75355. * Disposes of th webVRCOntroller
  75356. */
  75357. WebVRController.prototype.dispose = function () {
  75358. _super.prototype.dispose.call(this);
  75359. this.onTriggerStateChangedObservable.clear();
  75360. this.onMainButtonStateChangedObservable.clear();
  75361. this.onSecondaryButtonStateChangedObservable.clear();
  75362. this.onPadStateChangedObservable.clear();
  75363. this.onPadValuesChangedObservable.clear();
  75364. };
  75365. return WebVRController;
  75366. }(BABYLON.PoseEnabledController));
  75367. BABYLON.WebVRController = WebVRController;
  75368. })(BABYLON || (BABYLON = {}));
  75369. //# sourceMappingURL=babylon.webVRController.js.map
  75370. var BABYLON;
  75371. (function (BABYLON) {
  75372. /**
  75373. * Oculus Touch Controller
  75374. */
  75375. var OculusTouchController = /** @class */ (function (_super) {
  75376. __extends(OculusTouchController, _super);
  75377. /**
  75378. * Creates a new OculusTouchController from a gamepad
  75379. * @param vrGamepad the gamepad that the controller should be created from
  75380. */
  75381. function OculusTouchController(vrGamepad) {
  75382. var _this = _super.call(this, vrGamepad) || this;
  75383. /**
  75384. * Fired when the secondary trigger on this controller is modified
  75385. */
  75386. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  75387. /**
  75388. * Fired when the thumb rest on this controller is modified
  75389. */
  75390. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  75391. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  75392. return _this;
  75393. }
  75394. /**
  75395. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75396. * @param scene scene in which to add meshes
  75397. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75398. */
  75399. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75400. var _this = this;
  75401. var meshName;
  75402. // Hand
  75403. if (this.hand === 'left') {
  75404. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  75405. }
  75406. else { // Right is the default if no hand is specified
  75407. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  75408. }
  75409. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  75410. /*
  75411. Parent Mesh name: oculus_touch_left
  75412. - body
  75413. - trigger
  75414. - thumbstick
  75415. - grip
  75416. - button_y
  75417. - button_x
  75418. - button_enter
  75419. */
  75420. _this._defaultModel = newMeshes[1];
  75421. _this.attachToMesh(_this._defaultModel);
  75422. if (meshLoaded) {
  75423. meshLoaded(_this._defaultModel);
  75424. }
  75425. });
  75426. };
  75427. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75428. /**
  75429. * Fired when the A button on this controller is modified
  75430. */
  75431. get: function () {
  75432. if (this.hand === 'right') {
  75433. return this.onMainButtonStateChangedObservable;
  75434. }
  75435. else {
  75436. throw new Error('No A button on left hand');
  75437. }
  75438. },
  75439. enumerable: true,
  75440. configurable: true
  75441. });
  75442. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75443. /**
  75444. * Fired when the B button on this controller is modified
  75445. */
  75446. get: function () {
  75447. if (this.hand === 'right') {
  75448. return this.onSecondaryButtonStateChangedObservable;
  75449. }
  75450. else {
  75451. throw new Error('No B button on left hand');
  75452. }
  75453. },
  75454. enumerable: true,
  75455. configurable: true
  75456. });
  75457. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  75458. /**
  75459. * Fired when the X button on this controller is modified
  75460. */
  75461. get: function () {
  75462. if (this.hand === 'left') {
  75463. return this.onMainButtonStateChangedObservable;
  75464. }
  75465. else {
  75466. throw new Error('No X button on right hand');
  75467. }
  75468. },
  75469. enumerable: true,
  75470. configurable: true
  75471. });
  75472. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75473. /**
  75474. * Fired when the Y button on this controller is modified
  75475. */
  75476. get: function () {
  75477. if (this.hand === 'left') {
  75478. return this.onSecondaryButtonStateChangedObservable;
  75479. }
  75480. else {
  75481. throw new Error('No Y button on right hand');
  75482. }
  75483. },
  75484. enumerable: true,
  75485. configurable: true
  75486. });
  75487. /**
  75488. * Called once for each button that changed state since the last frame
  75489. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75490. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75491. * 2) secondary trigger (same)
  75492. * 3) A (right) X (left), touch, pressed = value
  75493. * 4) B / Y
  75494. * 5) thumb rest
  75495. * @param buttonIdx Which button index changed
  75496. * @param state New state of the button
  75497. * @param changes Which properties on the state changed since last frame
  75498. */
  75499. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75500. var notifyObject = state; //{ state: state, changes: changes };
  75501. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75502. switch (buttonIdx) {
  75503. case 0:
  75504. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75505. return;
  75506. case 1: // index trigger
  75507. if (this._defaultModel) {
  75508. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75509. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75510. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75511. }
  75512. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75513. return;
  75514. case 2: // secondary trigger
  75515. if (this._defaultModel) {
  75516. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75517. }
  75518. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  75519. return;
  75520. case 3:
  75521. if (this._defaultModel) {
  75522. if (notifyObject.pressed) {
  75523. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  75524. }
  75525. else {
  75526. (this._defaultModel.getChildren()[1]).position.y = 0;
  75527. }
  75528. }
  75529. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75530. return;
  75531. case 4:
  75532. if (this._defaultModel) {
  75533. if (notifyObject.pressed) {
  75534. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75535. }
  75536. else {
  75537. (this._defaultModel.getChildren()[2]).position.y = 0;
  75538. }
  75539. }
  75540. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75541. return;
  75542. case 5:
  75543. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  75544. return;
  75545. }
  75546. };
  75547. /**
  75548. * Base Url for the controller model.
  75549. */
  75550. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  75551. /**
  75552. * File name for the left controller model.
  75553. */
  75554. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  75555. /**
  75556. * File name for the right controller model.
  75557. */
  75558. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  75559. return OculusTouchController;
  75560. }(BABYLON.WebVRController));
  75561. BABYLON.OculusTouchController = OculusTouchController;
  75562. })(BABYLON || (BABYLON = {}));
  75563. //# sourceMappingURL=babylon.oculusTouchController.js.map
  75564. var BABYLON;
  75565. (function (BABYLON) {
  75566. /**
  75567. * Vive Controller
  75568. */
  75569. var ViveController = /** @class */ (function (_super) {
  75570. __extends(ViveController, _super);
  75571. /**
  75572. * Creates a new ViveController from a gamepad
  75573. * @param vrGamepad the gamepad that the controller should be created from
  75574. */
  75575. function ViveController(vrGamepad) {
  75576. var _this = _super.call(this, vrGamepad) || this;
  75577. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  75578. _this._invertLeftStickY = true;
  75579. return _this;
  75580. }
  75581. /**
  75582. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75583. * @param scene scene in which to add meshes
  75584. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75585. */
  75586. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75587. var _this = this;
  75588. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  75589. /*
  75590. Parent Mesh name: ViveWand
  75591. - body
  75592. - r_gripper
  75593. - l_gripper
  75594. - menu_button
  75595. - system_button
  75596. - trackpad
  75597. - trigger
  75598. - LED
  75599. */
  75600. _this._defaultModel = newMeshes[1];
  75601. _this.attachToMesh(_this._defaultModel);
  75602. if (meshLoaded) {
  75603. meshLoaded(_this._defaultModel);
  75604. }
  75605. });
  75606. };
  75607. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  75608. /**
  75609. * Fired when the left button on this controller is modified
  75610. */
  75611. get: function () {
  75612. return this.onMainButtonStateChangedObservable;
  75613. },
  75614. enumerable: true,
  75615. configurable: true
  75616. });
  75617. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  75618. /**
  75619. * Fired when the right button on this controller is modified
  75620. */
  75621. get: function () {
  75622. return this.onMainButtonStateChangedObservable;
  75623. },
  75624. enumerable: true,
  75625. configurable: true
  75626. });
  75627. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  75628. /**
  75629. * Fired when the menu button on this controller is modified
  75630. */
  75631. get: function () {
  75632. return this.onSecondaryButtonStateChangedObservable;
  75633. },
  75634. enumerable: true,
  75635. configurable: true
  75636. });
  75637. /**
  75638. * Called once for each button that changed state since the last frame
  75639. * Vive mapping:
  75640. * 0: touchpad
  75641. * 1: trigger
  75642. * 2: left AND right buttons
  75643. * 3: menu button
  75644. * @param buttonIdx Which button index changed
  75645. * @param state New state of the button
  75646. * @param changes Which properties on the state changed since last frame
  75647. */
  75648. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75649. var notifyObject = state; //{ state: state, changes: changes };
  75650. switch (buttonIdx) {
  75651. case 0:
  75652. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75653. return;
  75654. case 1: // index trigger
  75655. if (this._defaultModel) {
  75656. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  75657. }
  75658. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75659. return;
  75660. case 2: // left AND right button
  75661. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75662. return;
  75663. case 3:
  75664. if (this._defaultModel) {
  75665. if (notifyObject.pressed) {
  75666. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75667. }
  75668. else {
  75669. (this._defaultModel.getChildren()[2]).position.y = 0;
  75670. }
  75671. }
  75672. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75673. return;
  75674. }
  75675. };
  75676. /**
  75677. * Base Url for the controller model.
  75678. */
  75679. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  75680. /**
  75681. * File name for the controller model.
  75682. */
  75683. ViveController.MODEL_FILENAME = 'wand.babylon';
  75684. return ViveController;
  75685. }(BABYLON.WebVRController));
  75686. BABYLON.ViveController = ViveController;
  75687. })(BABYLON || (BABYLON = {}));
  75688. //# sourceMappingURL=babylon.viveController.js.map
  75689. var BABYLON;
  75690. (function (BABYLON) {
  75691. /**
  75692. * Generic Controller
  75693. */
  75694. var GenericController = /** @class */ (function (_super) {
  75695. __extends(GenericController, _super);
  75696. /**
  75697. * Creates a new GenericController from a gamepad
  75698. * @param vrGamepad the gamepad that the controller should be created from
  75699. */
  75700. function GenericController(vrGamepad) {
  75701. return _super.call(this, vrGamepad) || this;
  75702. }
  75703. /**
  75704. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75705. * @param scene scene in which to add meshes
  75706. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75707. */
  75708. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75709. var _this = this;
  75710. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75711. _this._defaultModel = newMeshes[1];
  75712. _this.attachToMesh(_this._defaultModel);
  75713. if (meshLoaded) {
  75714. meshLoaded(_this._defaultModel);
  75715. }
  75716. });
  75717. };
  75718. /**
  75719. * Called once for each button that changed state since the last frame
  75720. * @param buttonIdx Which button index changed
  75721. * @param state New state of the button
  75722. * @param changes Which properties on the state changed since last frame
  75723. */
  75724. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75725. console.log("Button id: " + buttonIdx + "state: ");
  75726. console.dir(state);
  75727. };
  75728. /**
  75729. * Base Url for the controller model.
  75730. */
  75731. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75732. /**
  75733. * File name for the controller model.
  75734. */
  75735. GenericController.MODEL_FILENAME = 'generic.babylon';
  75736. return GenericController;
  75737. }(BABYLON.WebVRController));
  75738. BABYLON.GenericController = GenericController;
  75739. })(BABYLON || (BABYLON = {}));
  75740. //# sourceMappingURL=babylon.genericController.js.map
  75741. var BABYLON;
  75742. (function (BABYLON) {
  75743. /**
  75744. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75745. */
  75746. var LoadedMeshInfo = /** @class */ (function () {
  75747. function LoadedMeshInfo() {
  75748. /**
  75749. * Map of the button meshes contained in the controller
  75750. */
  75751. this.buttonMeshes = {};
  75752. /**
  75753. * Map of the axis meshes contained in the controller
  75754. */
  75755. this.axisMeshes = {};
  75756. }
  75757. return LoadedMeshInfo;
  75758. }());
  75759. /**
  75760. * Defines the WindowsMotionController object that the state of the windows motion controller
  75761. */
  75762. var WindowsMotionController = /** @class */ (function (_super) {
  75763. __extends(WindowsMotionController, _super);
  75764. /**
  75765. * Creates a new WindowsMotionController from a gamepad
  75766. * @param vrGamepad the gamepad that the controller should be created from
  75767. */
  75768. function WindowsMotionController(vrGamepad) {
  75769. var _this = _super.call(this, vrGamepad) || this;
  75770. _this._mapping = {
  75771. // Semantic button names
  75772. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75773. // A mapping of the button name to glTF model node name
  75774. // that should be transformed by button value.
  75775. buttonMeshNames: {
  75776. 'trigger': 'SELECT',
  75777. 'menu': 'MENU',
  75778. 'grip': 'GRASP',
  75779. 'thumbstick': 'THUMBSTICK_PRESS',
  75780. 'trackpad': 'TOUCHPAD_PRESS'
  75781. },
  75782. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75783. buttonObservableNames: {
  75784. 'trigger': 'onTriggerStateChangedObservable',
  75785. 'menu': 'onSecondaryButtonStateChangedObservable',
  75786. 'grip': 'onMainButtonStateChangedObservable',
  75787. 'thumbstick': 'onPadStateChangedObservable',
  75788. 'trackpad': 'onTrackpadChangedObservable'
  75789. },
  75790. // A mapping of the axis name to glTF model node name
  75791. // that should be transformed by axis value.
  75792. // This array mirrors the browserGamepad.axes array, such that
  75793. // the mesh corresponding to axis 0 is in this array index 0.
  75794. axisMeshNames: [
  75795. 'THUMBSTICK_X',
  75796. 'THUMBSTICK_Y',
  75797. 'TOUCHPAD_TOUCH_X',
  75798. 'TOUCHPAD_TOUCH_Y'
  75799. ],
  75800. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75801. };
  75802. /**
  75803. * Fired when the trackpad on this controller is clicked
  75804. */
  75805. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75806. /**
  75807. * Fired when the trackpad on this controller is modified
  75808. */
  75809. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75810. /**
  75811. * The current x and y values of this controller's trackpad
  75812. */
  75813. _this.trackpad = { x: 0, y: 0 };
  75814. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75815. _this._loadedMeshInfo = null;
  75816. return _this;
  75817. }
  75818. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75819. /**
  75820. * Fired when the trigger on this controller is modified
  75821. */
  75822. get: function () {
  75823. return this.onTriggerStateChangedObservable;
  75824. },
  75825. enumerable: true,
  75826. configurable: true
  75827. });
  75828. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75829. /**
  75830. * Fired when the menu button on this controller is modified
  75831. */
  75832. get: function () {
  75833. return this.onSecondaryButtonStateChangedObservable;
  75834. },
  75835. enumerable: true,
  75836. configurable: true
  75837. });
  75838. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75839. /**
  75840. * Fired when the grip button on this controller is modified
  75841. */
  75842. get: function () {
  75843. return this.onMainButtonStateChangedObservable;
  75844. },
  75845. enumerable: true,
  75846. configurable: true
  75847. });
  75848. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75849. /**
  75850. * Fired when the thumbstick button on this controller is modified
  75851. */
  75852. get: function () {
  75853. return this.onPadStateChangedObservable;
  75854. },
  75855. enumerable: true,
  75856. configurable: true
  75857. });
  75858. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75859. /**
  75860. * Fired when the touchpad button on this controller is modified
  75861. */
  75862. get: function () {
  75863. return this.onTrackpadChangedObservable;
  75864. },
  75865. enumerable: true,
  75866. configurable: true
  75867. });
  75868. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75869. /**
  75870. * Fired when the touchpad values on this controller are modified
  75871. */
  75872. get: function () {
  75873. return this.onTrackpadValuesChangedObservable;
  75874. },
  75875. enumerable: true,
  75876. configurable: true
  75877. });
  75878. WindowsMotionController.prototype._updateTrackpad = function () {
  75879. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75880. this.trackpad.x = this.browserGamepad["axes"][2];
  75881. this.trackpad.y = this.browserGamepad["axes"][3];
  75882. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75883. }
  75884. };
  75885. /**
  75886. * Called once per frame by the engine.
  75887. */
  75888. WindowsMotionController.prototype.update = function () {
  75889. _super.prototype.update.call(this);
  75890. if (this.browserGamepad.axes) {
  75891. this._updateTrackpad();
  75892. // Only need to animate axes if there is a loaded mesh
  75893. if (this._loadedMeshInfo) {
  75894. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75895. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75896. }
  75897. }
  75898. }
  75899. };
  75900. /**
  75901. * Called once for each button that changed state since the last frame
  75902. * @param buttonIdx Which button index changed
  75903. * @param state New state of the button
  75904. * @param changes Which properties on the state changed since last frame
  75905. */
  75906. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75907. var buttonName = this._mapping.buttons[buttonIdx];
  75908. if (!buttonName) {
  75909. return;
  75910. }
  75911. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75912. this._updateTrackpad();
  75913. // Only emit events for buttons that we know how to map from index to name
  75914. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75915. if (observable) {
  75916. observable.notifyObservers(state);
  75917. }
  75918. this._lerpButtonTransform(buttonName, state.value);
  75919. };
  75920. /**
  75921. * Moves the buttons on the controller mesh based on their current state
  75922. * @param buttonName the name of the button to move
  75923. * @param buttonValue the value of the button which determines the buttons new position
  75924. */
  75925. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75926. // If there is no loaded mesh, there is nothing to transform.
  75927. if (!this._loadedMeshInfo) {
  75928. return;
  75929. }
  75930. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75931. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75932. return;
  75933. }
  75934. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75935. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75936. };
  75937. /**
  75938. * Moves the axis on the controller mesh based on its current state
  75939. * @param axis the index of the axis
  75940. * @param axisValue the value of the axis which determines the meshes new position
  75941. * @hidden
  75942. */
  75943. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75944. if (!this._loadedMeshInfo) {
  75945. return;
  75946. }
  75947. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75948. if (!meshInfo) {
  75949. return;
  75950. }
  75951. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75952. return;
  75953. }
  75954. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75955. var lerpValue = axisValue * 0.5 + 0.5;
  75956. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75957. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75958. };
  75959. /**
  75960. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75961. * @param scene scene in which to add meshes
  75962. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75963. */
  75964. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75965. var _this = this;
  75966. if (forceDefault === void 0) { forceDefault = false; }
  75967. var path;
  75968. var filename;
  75969. // Checking if GLB loader is present
  75970. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75971. // Determine the device specific folder based on the ID suffix
  75972. var device = 'default';
  75973. if (this.id && !forceDefault) {
  75974. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75975. device = ((match && match[0]) || device);
  75976. }
  75977. // Hand
  75978. if (this.hand === 'left') {
  75979. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75980. }
  75981. else { // Right is the default if no hand is specified
  75982. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75983. }
  75984. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75985. }
  75986. else {
  75987. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75988. path = BABYLON.GenericController.MODEL_BASE_URL;
  75989. filename = BABYLON.GenericController.MODEL_FILENAME;
  75990. }
  75991. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75992. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75993. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75994. if (!_this._loadedMeshInfo) {
  75995. return;
  75996. }
  75997. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75998. _this.attachToMesh(_this._defaultModel);
  75999. if (meshLoaded) {
  76000. meshLoaded(_this._defaultModel);
  76001. }
  76002. }, null, function (scene, message) {
  76003. BABYLON.Tools.Log(message);
  76004. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76005. if (!forceDefault) {
  76006. _this.initControllerMesh(scene, meshLoaded, true);
  76007. }
  76008. });
  76009. };
  76010. /**
  76011. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76012. * can be transformed by button presses and axes values, based on this._mapping.
  76013. *
  76014. * @param scene scene in which the meshes exist
  76015. * @param meshes list of meshes that make up the controller model to process
  76016. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76017. */
  76018. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76019. var loadedMeshInfo = null;
  76020. // Create a new mesh to contain the glTF hierarchy
  76021. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76022. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76023. var childMesh = null;
  76024. for (var i = 0; i < meshes.length; i++) {
  76025. var mesh = meshes[i];
  76026. if (!mesh.parent) {
  76027. // Exclude controller meshes from picking results
  76028. mesh.isPickable = false;
  76029. // Handle root node, attach to the new parentMesh
  76030. childMesh = mesh;
  76031. break;
  76032. }
  76033. }
  76034. if (childMesh) {
  76035. childMesh.setParent(parentMesh);
  76036. // Create our mesh info. Note that this method will always return non-null.
  76037. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76038. }
  76039. else {
  76040. BABYLON.Tools.Warn('Could not find root node in model file.');
  76041. }
  76042. return loadedMeshInfo;
  76043. };
  76044. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76045. var loadedMeshInfo = new LoadedMeshInfo();
  76046. var i;
  76047. loadedMeshInfo.rootNode = rootNode;
  76048. // Reset the caches
  76049. loadedMeshInfo.buttonMeshes = {};
  76050. loadedMeshInfo.axisMeshes = {};
  76051. // Button Meshes
  76052. for (i = 0; i < this._mapping.buttons.length; i++) {
  76053. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76054. if (!buttonMeshName) {
  76055. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76056. continue;
  76057. }
  76058. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76059. if (!buttonMesh) {
  76060. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76061. continue;
  76062. }
  76063. var buttonMeshInfo = {
  76064. index: i,
  76065. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76066. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76067. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76068. };
  76069. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76070. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76071. }
  76072. else {
  76073. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76074. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76075. '(VALUE: ' + !!buttonMeshInfo.value +
  76076. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76077. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76078. ')');
  76079. }
  76080. }
  76081. // Axis Meshes
  76082. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76083. var axisMeshName = this._mapping.axisMeshNames[i];
  76084. if (!axisMeshName) {
  76085. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76086. continue;
  76087. }
  76088. var axisMesh = getChildByName(rootNode, axisMeshName);
  76089. if (!axisMesh) {
  76090. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76091. continue;
  76092. }
  76093. var axisMeshInfo = {
  76094. index: i,
  76095. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76096. min: getImmediateChildByName(axisMesh, 'MIN'),
  76097. max: getImmediateChildByName(axisMesh, 'MAX')
  76098. };
  76099. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76100. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76101. }
  76102. else {
  76103. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76104. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76105. '(VALUE: ' + !!axisMeshInfo.value +
  76106. ', MIN: ' + !!axisMeshInfo.min +
  76107. ', MAX:' + !!axisMeshInfo.max +
  76108. ')');
  76109. }
  76110. }
  76111. // Pointing Ray
  76112. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76113. if (!loadedMeshInfo.pointingPoseNode) {
  76114. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76115. }
  76116. else {
  76117. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76118. }
  76119. return loadedMeshInfo;
  76120. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76121. function getChildByName(node, name) {
  76122. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76123. }
  76124. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76125. function getImmediateChildByName(node, name) {
  76126. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76127. }
  76128. };
  76129. /**
  76130. * Gets the ray of the controller in the direction the controller is pointing
  76131. * @param length the length the resulting ray should be
  76132. * @returns a ray in the direction the controller is pointing
  76133. */
  76134. WindowsMotionController.prototype.getForwardRay = function (length) {
  76135. if (length === void 0) { length = 100; }
  76136. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76137. return _super.prototype.getForwardRay.call(this, length);
  76138. }
  76139. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76140. var origin = m.getTranslation();
  76141. var forward = new BABYLON.Vector3(0, 0, -1);
  76142. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76143. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76144. return new BABYLON.Ray(origin, direction, length);
  76145. };
  76146. /**
  76147. * Disposes of the controller
  76148. */
  76149. WindowsMotionController.prototype.dispose = function () {
  76150. _super.prototype.dispose.call(this);
  76151. this.onTrackpadChangedObservable.clear();
  76152. };
  76153. /**
  76154. * The base url used to load the left and right controller models
  76155. */
  76156. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76157. /**
  76158. * The name of the left controller model file
  76159. */
  76160. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76161. /**
  76162. * The name of the right controller model file
  76163. */
  76164. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76165. /**
  76166. * The controller name prefix for this controller type
  76167. */
  76168. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76169. /**
  76170. * The controller id pattern for this controller type
  76171. */
  76172. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76173. return WindowsMotionController;
  76174. }(BABYLON.WebVRController));
  76175. BABYLON.WindowsMotionController = WindowsMotionController;
  76176. })(BABYLON || (BABYLON = {}));
  76177. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76178. var BABYLON;
  76179. (function (BABYLON) {
  76180. /**
  76181. * Gear VR Controller
  76182. */
  76183. var GearVRController = /** @class */ (function (_super) {
  76184. __extends(GearVRController, _super);
  76185. /**
  76186. * Creates a new GearVRController from a gamepad
  76187. * @param vrGamepad the gamepad that the controller should be created from
  76188. */
  76189. function GearVRController(vrGamepad) {
  76190. var _this = _super.call(this, vrGamepad) || this;
  76191. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76192. _this._draggedRoomRotation = 0;
  76193. _this._tmpVector = new BABYLON.Vector3();
  76194. _this._buttonIndexToObservableNameMap = [
  76195. 'onTrackpadChangedObservable',
  76196. 'onTriggerStateChangedObservable' // Trigger
  76197. ];
  76198. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76199. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76200. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76201. return _this;
  76202. }
  76203. /**
  76204. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76205. * @param poseData raw pose fromthe device
  76206. */
  76207. GearVRController.prototype.updateFromDevice = function (poseData) {
  76208. _super.prototype.updateFromDevice.call(this, poseData);
  76209. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76210. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76211. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76212. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76213. // Find the radian distance away that the headset is from the controllers rotation
  76214. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76215. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76216. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76217. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76218. this._draggedRoomRotation += rotationAmount;
  76219. // Rotate controller around headset
  76220. var sin = Math.sin(-rotationAmount);
  76221. var cos = Math.cos(-rotationAmount);
  76222. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76223. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76224. }
  76225. }
  76226. }
  76227. };
  76228. /**
  76229. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76230. * @param scene scene in which to add meshes
  76231. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76232. */
  76233. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76234. var _this = this;
  76235. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76236. // Offset the controller so it will rotate around the users wrist
  76237. var mesh = new BABYLON.Mesh("", scene);
  76238. newMeshes[1].parent = mesh;
  76239. newMeshes[1].position.z = -0.15;
  76240. _this._defaultModel = mesh;
  76241. _this.attachToMesh(_this._defaultModel);
  76242. if (meshLoaded) {
  76243. meshLoaded(_this._defaultModel);
  76244. }
  76245. });
  76246. };
  76247. /**
  76248. * Called once for each button that changed state since the last frame
  76249. * @param buttonIdx Which button index changed
  76250. * @param state New state of the button
  76251. * @param changes Which properties on the state changed since last frame
  76252. */
  76253. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76254. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  76255. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  76256. // Only emit events for buttons that we know how to map from index to observable
  76257. var observable = this[observableName];
  76258. if (observable) {
  76259. observable.notifyObservers(state);
  76260. }
  76261. }
  76262. };
  76263. /**
  76264. * Base Url for the controller model.
  76265. */
  76266. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76267. /**
  76268. * File name for the controller model.
  76269. */
  76270. GearVRController.MODEL_FILENAME = 'generic.babylon';
  76271. /**
  76272. * Gamepad Id prefix used to identify this controller.
  76273. */
  76274. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  76275. return GearVRController;
  76276. }(BABYLON.WebVRController));
  76277. BABYLON.GearVRController = GearVRController;
  76278. })(BABYLON || (BABYLON = {}));
  76279. //# sourceMappingURL=babylon.gearVRController.js.map
  76280. var BABYLON;
  76281. (function (BABYLON) {
  76282. /**
  76283. * Google Daydream controller
  76284. */
  76285. var DaydreamController = /** @class */ (function (_super) {
  76286. __extends(DaydreamController, _super);
  76287. /**
  76288. * Creates a new DaydreamController from a gamepad
  76289. * @param vrGamepad the gamepad that the controller should be created from
  76290. */
  76291. function DaydreamController(vrGamepad) {
  76292. var _this = _super.call(this, vrGamepad) || this;
  76293. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  76294. return _this;
  76295. }
  76296. /**
  76297. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76298. * @param scene scene in which to add meshes
  76299. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76300. */
  76301. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76302. var _this = this;
  76303. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  76304. _this._defaultModel = newMeshes[1];
  76305. _this.attachToMesh(_this._defaultModel);
  76306. if (meshLoaded) {
  76307. meshLoaded(_this._defaultModel);
  76308. }
  76309. });
  76310. };
  76311. /**
  76312. * Called once for each button that changed state since the last frame
  76313. * @param buttonIdx Which button index changed
  76314. * @param state New state of the button
  76315. * @param changes Which properties on the state changed since last frame
  76316. */
  76317. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76318. // Daydream controller only has 1 GamepadButton (on the trackpad).
  76319. if (buttonIdx === 0) {
  76320. var observable = this.onTriggerStateChangedObservable;
  76321. if (observable) {
  76322. observable.notifyObservers(state);
  76323. }
  76324. }
  76325. else {
  76326. // If the app or home buttons are ever made available
  76327. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  76328. }
  76329. };
  76330. /**
  76331. * Base Url for the controller model.
  76332. */
  76333. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76334. /**
  76335. * File name for the controller model.
  76336. */
  76337. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  76338. /**
  76339. * Gamepad Id prefix used to identify Daydream Controller.
  76340. */
  76341. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  76342. return DaydreamController;
  76343. }(BABYLON.WebVRController));
  76344. BABYLON.DaydreamController = DaydreamController;
  76345. })(BABYLON || (BABYLON = {}));
  76346. //# sourceMappingURL=babylon.daydreamController.js.map
  76347. var BABYLON;
  76348. (function (BABYLON) {
  76349. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  76350. get: function () {
  76351. if (!this._gamepadManager) {
  76352. this._gamepadManager = new BABYLON.GamepadManager(this);
  76353. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  76354. if (!component) {
  76355. component = new GamepadSystemSceneComponent(this);
  76356. this._addComponent(component);
  76357. }
  76358. }
  76359. return this._gamepadManager;
  76360. },
  76361. enumerable: true,
  76362. configurable: true
  76363. });
  76364. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  76365. this.add(new BABYLON.FreeCameraGamepadInput());
  76366. return this;
  76367. };
  76368. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  76369. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  76370. return this;
  76371. };
  76372. /**
  76373. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  76374. */
  76375. var GamepadSystemSceneComponent = /** @class */ (function () {
  76376. /**
  76377. * Creates a new instance of the component for the given scene
  76378. * @param scene Defines the scene to register the component in
  76379. */
  76380. function GamepadSystemSceneComponent(scene) {
  76381. /**
  76382. * The component name helpfull to identify the component in the list of scene components.
  76383. */
  76384. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  76385. this.scene = scene;
  76386. }
  76387. /**
  76388. * Registers the component in a given scene
  76389. */
  76390. GamepadSystemSceneComponent.prototype.register = function () {
  76391. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  76392. };
  76393. /**
  76394. * Rebuilds the elements related to this component in case of
  76395. * context lost for instance.
  76396. */
  76397. GamepadSystemSceneComponent.prototype.rebuild = function () {
  76398. // Nothing to do for gamepads
  76399. };
  76400. /**
  76401. * Disposes the component and the associated ressources
  76402. */
  76403. GamepadSystemSceneComponent.prototype.dispose = function () {
  76404. var gamepadManager = this.scene._gamepadManager;
  76405. if (gamepadManager) {
  76406. gamepadManager.dispose();
  76407. this.scene._gamepadManager = null;
  76408. }
  76409. };
  76410. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  76411. var gamepadManager = this.scene._gamepadManager;
  76412. if (gamepadManager && gamepadManager._isMonitoring) {
  76413. gamepadManager._checkGamepadsStatus();
  76414. }
  76415. };
  76416. return GamepadSystemSceneComponent;
  76417. }());
  76418. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  76419. })(BABYLON || (BABYLON = {}));
  76420. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  76421. var BABYLON;
  76422. (function (BABYLON) {
  76423. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  76424. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  76425. });
  76426. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76427. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76428. });
  76429. var FollowCamera = /** @class */ (function (_super) {
  76430. __extends(FollowCamera, _super);
  76431. function FollowCamera(name, position, scene, lockedTarget) {
  76432. if (lockedTarget === void 0) { lockedTarget = null; }
  76433. var _this = _super.call(this, name, position, scene) || this;
  76434. _this.radius = 12;
  76435. _this.rotationOffset = 0;
  76436. _this.heightOffset = 4;
  76437. _this.cameraAcceleration = 0.05;
  76438. _this.maxCameraSpeed = 20;
  76439. _this.lockedTarget = lockedTarget;
  76440. return _this;
  76441. }
  76442. FollowCamera.prototype.getRadians = function (degrees) {
  76443. return degrees * Math.PI / 180;
  76444. };
  76445. FollowCamera.prototype.follow = function (cameraTarget) {
  76446. if (!cameraTarget)
  76447. return;
  76448. var yRotation;
  76449. if (cameraTarget.rotationQuaternion) {
  76450. var rotMatrix = new BABYLON.Matrix();
  76451. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76452. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76453. }
  76454. else {
  76455. yRotation = cameraTarget.rotation.y;
  76456. }
  76457. var radians = this.getRadians(this.rotationOffset) + yRotation;
  76458. var targetPosition = cameraTarget.getAbsolutePosition();
  76459. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76460. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76461. var dx = targetX - this.position.x;
  76462. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76463. var dz = (targetZ) - this.position.z;
  76464. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76465. var vy = dy * this.cameraAcceleration;
  76466. var vz = dz * this.cameraAcceleration * 2;
  76467. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76468. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76469. }
  76470. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76471. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76472. }
  76473. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76474. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76475. }
  76476. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76477. this.setTarget(targetPosition);
  76478. };
  76479. /** @hidden */
  76480. FollowCamera.prototype._checkInputs = function () {
  76481. _super.prototype._checkInputs.call(this);
  76482. if (this.lockedTarget) {
  76483. this.follow(this.lockedTarget);
  76484. }
  76485. };
  76486. FollowCamera.prototype.getClassName = function () {
  76487. return "FollowCamera";
  76488. };
  76489. __decorate([
  76490. BABYLON.serialize()
  76491. ], FollowCamera.prototype, "radius", void 0);
  76492. __decorate([
  76493. BABYLON.serialize()
  76494. ], FollowCamera.prototype, "rotationOffset", void 0);
  76495. __decorate([
  76496. BABYLON.serialize()
  76497. ], FollowCamera.prototype, "heightOffset", void 0);
  76498. __decorate([
  76499. BABYLON.serialize()
  76500. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76501. __decorate([
  76502. BABYLON.serialize()
  76503. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76504. __decorate([
  76505. BABYLON.serializeAsMeshReference("lockedTargetId")
  76506. ], FollowCamera.prototype, "lockedTarget", void 0);
  76507. return FollowCamera;
  76508. }(BABYLON.TargetCamera));
  76509. BABYLON.FollowCamera = FollowCamera;
  76510. var ArcFollowCamera = /** @class */ (function (_super) {
  76511. __extends(ArcFollowCamera, _super);
  76512. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76513. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76514. _this.alpha = alpha;
  76515. _this.beta = beta;
  76516. _this.radius = radius;
  76517. _this.target = target;
  76518. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  76519. _this.follow();
  76520. return _this;
  76521. }
  76522. ArcFollowCamera.prototype.follow = function () {
  76523. if (!this.target) {
  76524. return;
  76525. }
  76526. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  76527. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  76528. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  76529. var targetPosition = this.target.getAbsolutePosition();
  76530. this.position = targetPosition.add(this._cartesianCoordinates);
  76531. this.setTarget(targetPosition);
  76532. };
  76533. /** @hidden */
  76534. ArcFollowCamera.prototype._checkInputs = function () {
  76535. _super.prototype._checkInputs.call(this);
  76536. this.follow();
  76537. };
  76538. ArcFollowCamera.prototype.getClassName = function () {
  76539. return "ArcFollowCamera";
  76540. };
  76541. return ArcFollowCamera;
  76542. }(BABYLON.TargetCamera));
  76543. BABYLON.ArcFollowCamera = ArcFollowCamera;
  76544. })(BABYLON || (BABYLON = {}));
  76545. //# sourceMappingURL=babylon.followCamera.js.map
  76546. var BABYLON;
  76547. (function (BABYLON) {
  76548. // We're mainly based on the logic defined into the FreeCamera code
  76549. var UniversalCamera = /** @class */ (function (_super) {
  76550. __extends(UniversalCamera, _super);
  76551. //-- end properties for backward compatibility for inputs
  76552. function UniversalCamera(name, position, scene) {
  76553. var _this = _super.call(this, name, position, scene) || this;
  76554. _this.inputs.addGamepad();
  76555. return _this;
  76556. }
  76557. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  76558. //-- Begin properties for backward compatibility for inputs
  76559. get: function () {
  76560. var gamepad = this.inputs.attached["gamepad"];
  76561. if (gamepad)
  76562. return gamepad.gamepadAngularSensibility;
  76563. return 0;
  76564. },
  76565. set: function (value) {
  76566. var gamepad = this.inputs.attached["gamepad"];
  76567. if (gamepad)
  76568. gamepad.gamepadAngularSensibility = value;
  76569. },
  76570. enumerable: true,
  76571. configurable: true
  76572. });
  76573. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  76574. get: function () {
  76575. var gamepad = this.inputs.attached["gamepad"];
  76576. if (gamepad)
  76577. return gamepad.gamepadMoveSensibility;
  76578. return 0;
  76579. },
  76580. set: function (value) {
  76581. var gamepad = this.inputs.attached["gamepad"];
  76582. if (gamepad)
  76583. gamepad.gamepadMoveSensibility = value;
  76584. },
  76585. enumerable: true,
  76586. configurable: true
  76587. });
  76588. UniversalCamera.prototype.getClassName = function () {
  76589. return "UniversalCamera";
  76590. };
  76591. return UniversalCamera;
  76592. }(BABYLON.TouchCamera));
  76593. BABYLON.UniversalCamera = UniversalCamera;
  76594. })(BABYLON || (BABYLON = {}));
  76595. //# sourceMappingURL=babylon.universalCamera.js.map
  76596. var BABYLON;
  76597. (function (BABYLON) {
  76598. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  76599. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  76600. });
  76601. // We're mainly based on the logic defined into the FreeCamera code
  76602. var GamepadCamera = /** @class */ (function (_super) {
  76603. __extends(GamepadCamera, _super);
  76604. //-- end properties for backward compatibility for inputs
  76605. function GamepadCamera(name, position, scene) {
  76606. return _super.call(this, name, position, scene) || this;
  76607. }
  76608. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  76609. //-- Begin properties for backward compatibility for inputs
  76610. get: function () {
  76611. var gamepad = this.inputs.attached["gamepad"];
  76612. if (gamepad)
  76613. return gamepad.gamepadAngularSensibility;
  76614. return 0;
  76615. },
  76616. set: function (value) {
  76617. var gamepad = this.inputs.attached["gamepad"];
  76618. if (gamepad)
  76619. gamepad.gamepadAngularSensibility = value;
  76620. },
  76621. enumerable: true,
  76622. configurable: true
  76623. });
  76624. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  76625. get: function () {
  76626. var gamepad = this.inputs.attached["gamepad"];
  76627. if (gamepad)
  76628. return gamepad.gamepadMoveSensibility;
  76629. return 0;
  76630. },
  76631. set: function (value) {
  76632. var gamepad = this.inputs.attached["gamepad"];
  76633. if (gamepad)
  76634. gamepad.gamepadMoveSensibility = value;
  76635. },
  76636. enumerable: true,
  76637. configurable: true
  76638. });
  76639. GamepadCamera.prototype.getClassName = function () {
  76640. return "GamepadCamera";
  76641. };
  76642. return GamepadCamera;
  76643. }(BABYLON.UniversalCamera));
  76644. BABYLON.GamepadCamera = GamepadCamera;
  76645. })(BABYLON || (BABYLON = {}));
  76646. //# sourceMappingURL=babylon.gamepadCamera.js.map
  76647. var BABYLON;
  76648. (function (BABYLON) {
  76649. var PostProcessRenderPipelineManager = /** @class */ (function () {
  76650. function PostProcessRenderPipelineManager() {
  76651. this._renderPipelines = {};
  76652. }
  76653. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  76654. this._renderPipelines[renderPipeline._name] = renderPipeline;
  76655. };
  76656. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  76657. if (unique === void 0) { unique = false; }
  76658. var renderPipeline = this._renderPipelines[renderPipelineName];
  76659. if (!renderPipeline) {
  76660. return;
  76661. }
  76662. renderPipeline._attachCameras(cameras, unique);
  76663. };
  76664. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  76665. var renderPipeline = this._renderPipelines[renderPipelineName];
  76666. if (!renderPipeline) {
  76667. return;
  76668. }
  76669. renderPipeline._detachCameras(cameras);
  76670. };
  76671. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76672. var renderPipeline = this._renderPipelines[renderPipelineName];
  76673. if (!renderPipeline) {
  76674. return;
  76675. }
  76676. renderPipeline._enableEffect(renderEffectName, cameras);
  76677. };
  76678. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76679. var renderPipeline = this._renderPipelines[renderPipelineName];
  76680. if (!renderPipeline) {
  76681. return;
  76682. }
  76683. renderPipeline._disableEffect(renderEffectName, cameras);
  76684. };
  76685. PostProcessRenderPipelineManager.prototype.update = function () {
  76686. for (var renderPipelineName in this._renderPipelines) {
  76687. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76688. var pipeline = this._renderPipelines[renderPipelineName];
  76689. if (!pipeline.isSupported) {
  76690. pipeline.dispose();
  76691. delete this._renderPipelines[renderPipelineName];
  76692. }
  76693. else {
  76694. pipeline._update();
  76695. }
  76696. }
  76697. }
  76698. };
  76699. /** @hidden */
  76700. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76701. for (var renderPipelineName in this._renderPipelines) {
  76702. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76703. var pipeline = this._renderPipelines[renderPipelineName];
  76704. pipeline._rebuild();
  76705. }
  76706. }
  76707. };
  76708. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76709. for (var renderPipelineName in this._renderPipelines) {
  76710. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76711. var pipeline = this._renderPipelines[renderPipelineName];
  76712. pipeline.dispose();
  76713. }
  76714. }
  76715. };
  76716. return PostProcessRenderPipelineManager;
  76717. }());
  76718. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76719. })(BABYLON || (BABYLON = {}));
  76720. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76721. var BABYLON;
  76722. (function (BABYLON) {
  76723. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76724. get: function () {
  76725. if (!this._postProcessRenderPipelineManager) {
  76726. // Register the G Buffer component to the scene.
  76727. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76728. if (!component) {
  76729. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76730. this._addComponent(component);
  76731. }
  76732. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76733. }
  76734. return this._postProcessRenderPipelineManager;
  76735. },
  76736. enumerable: true,
  76737. configurable: true
  76738. });
  76739. /**
  76740. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76741. */
  76742. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76743. /**
  76744. * Creates a new instance of the component for the given scene
  76745. * @param scene Defines the scene to register the component in
  76746. */
  76747. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76748. /**
  76749. * The component name helpfull to identify the component in the list of scene components.
  76750. */
  76751. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76752. this.scene = scene;
  76753. }
  76754. /**
  76755. * Registers the component in a given scene
  76756. */
  76757. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76758. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76759. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76760. };
  76761. /**
  76762. * Rebuilds the elements related to this component in case of
  76763. * context lost for instance.
  76764. */
  76765. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76766. // Nothing to do for this component
  76767. };
  76768. /**
  76769. * Disposes the component and the associated ressources
  76770. */
  76771. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76772. if (this.scene._postProcessRenderPipelineManager) {
  76773. this.scene._postProcessRenderPipelineManager.dispose();
  76774. }
  76775. };
  76776. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76777. if (this.scene._postProcessRenderPipelineManager) {
  76778. this.scene._postProcessRenderPipelineManager.update();
  76779. }
  76780. };
  76781. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76782. if (this.scene._postProcessRenderPipelineManager) {
  76783. this.scene._postProcessRenderPipelineManager._rebuild();
  76784. }
  76785. };
  76786. return PostProcessRenderPipelineManagerSceneComponent;
  76787. }());
  76788. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76789. })(BABYLON || (BABYLON = {}));
  76790. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76791. var BABYLON;
  76792. (function (BABYLON) {
  76793. /**
  76794. * This represents a set of one or more post processes in Babylon.
  76795. * A post process can be used to apply a shader to a texture after it is rendered.
  76796. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76797. */
  76798. var PostProcessRenderEffect = /** @class */ (function () {
  76799. /**
  76800. * Instantiates a post process render effect.
  76801. * A post process can be used to apply a shader to a texture after it is rendered.
  76802. * @param engine The engine the effect is tied to
  76803. * @param name The name of the effect
  76804. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76805. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76806. */
  76807. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76808. this._name = name;
  76809. this._singleInstance = singleInstance || true;
  76810. this._getPostProcesses = getPostProcesses;
  76811. this._cameras = {};
  76812. this._indicesForCamera = {};
  76813. this._postProcesses = {};
  76814. }
  76815. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76816. /**
  76817. * Checks if all the post processes in the effect are supported.
  76818. */
  76819. get: function () {
  76820. for (var index in this._postProcesses) {
  76821. if (this._postProcesses.hasOwnProperty(index)) {
  76822. var pps = this._postProcesses[index];
  76823. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76824. if (!pps[ppIndex].isSupported) {
  76825. return false;
  76826. }
  76827. }
  76828. }
  76829. }
  76830. return true;
  76831. },
  76832. enumerable: true,
  76833. configurable: true
  76834. });
  76835. /**
  76836. * Updates the current state of the effect
  76837. * @hidden
  76838. */
  76839. PostProcessRenderEffect.prototype._update = function () {
  76840. };
  76841. /**
  76842. * Attaches the effect on cameras
  76843. * @param cameras The camera to attach to.
  76844. * @hidden
  76845. */
  76846. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76847. var _this = this;
  76848. var cameraKey;
  76849. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76850. if (!cams) {
  76851. return;
  76852. }
  76853. for (var i = 0; i < cams.length; i++) {
  76854. var camera = cams[i];
  76855. var cameraName = camera.name;
  76856. if (this._singleInstance) {
  76857. cameraKey = 0;
  76858. }
  76859. else {
  76860. cameraKey = cameraName;
  76861. }
  76862. if (!this._postProcesses[cameraKey]) {
  76863. var postProcess = this._getPostProcesses();
  76864. if (postProcess) {
  76865. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76866. }
  76867. }
  76868. if (!this._indicesForCamera[cameraName]) {
  76869. this._indicesForCamera[cameraName] = [];
  76870. }
  76871. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76872. var index = camera.attachPostProcess(postProcess);
  76873. _this._indicesForCamera[cameraName].push(index);
  76874. });
  76875. if (!this._cameras[cameraName]) {
  76876. this._cameras[cameraName] = camera;
  76877. }
  76878. }
  76879. };
  76880. /**
  76881. * Detatches the effect on cameras
  76882. * @param cameras The camera to detatch from.
  76883. * @hidden
  76884. */
  76885. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76886. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76887. if (!cams) {
  76888. return;
  76889. }
  76890. for (var i = 0; i < cams.length; i++) {
  76891. var camera = cams[i];
  76892. var cameraName = camera.name;
  76893. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76894. camera.detachPostProcess(postProcess);
  76895. });
  76896. if (this._cameras[cameraName]) {
  76897. //this._indicesForCamera.splice(index, 1);
  76898. this._cameras[cameraName] = null;
  76899. }
  76900. }
  76901. };
  76902. /**
  76903. * Enables the effect on given cameras
  76904. * @param cameras The camera to enable.
  76905. * @hidden
  76906. */
  76907. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76908. var _this = this;
  76909. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76910. if (!cams) {
  76911. return;
  76912. }
  76913. for (var i = 0; i < cams.length; i++) {
  76914. var camera = cams[i];
  76915. var cameraName = camera.name;
  76916. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76917. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76918. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76919. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76920. });
  76921. }
  76922. }
  76923. }
  76924. };
  76925. /**
  76926. * Disables the effect on the given cameras
  76927. * @param cameras The camera to disable.
  76928. * @hidden
  76929. */
  76930. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76931. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76932. if (!cams) {
  76933. return;
  76934. }
  76935. for (var i = 0; i < cams.length; i++) {
  76936. var camera = cams[i];
  76937. var cameraName = camera.name;
  76938. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76939. camera.detachPostProcess(postProcess);
  76940. });
  76941. }
  76942. };
  76943. /**
  76944. * Gets a list of the post processes contained in the effect.
  76945. * @param camera The camera to get the post processes on.
  76946. * @returns The list of the post processes in the effect.
  76947. */
  76948. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76949. if (this._singleInstance) {
  76950. return this._postProcesses[0];
  76951. }
  76952. else {
  76953. if (!camera) {
  76954. return null;
  76955. }
  76956. return this._postProcesses[camera.name];
  76957. }
  76958. };
  76959. return PostProcessRenderEffect;
  76960. }());
  76961. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76962. })(BABYLON || (BABYLON = {}));
  76963. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76964. var BABYLON;
  76965. (function (BABYLON) {
  76966. var PostProcessRenderPipeline = /** @class */ (function () {
  76967. function PostProcessRenderPipeline(engine, name) {
  76968. this.engine = engine;
  76969. this._name = name;
  76970. this._renderEffects = {};
  76971. this._renderEffectsForIsolatedPass = new Array();
  76972. this._cameras = [];
  76973. }
  76974. PostProcessRenderPipeline.prototype.getClassName = function () {
  76975. return "PostProcessRenderPipeline";
  76976. };
  76977. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76978. get: function () {
  76979. for (var renderEffectName in this._renderEffects) {
  76980. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76981. if (!this._renderEffects[renderEffectName].isSupported) {
  76982. return false;
  76983. }
  76984. }
  76985. }
  76986. return true;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76992. this._renderEffects[renderEffect._name] = renderEffect;
  76993. };
  76994. // private
  76995. /** @hidden */
  76996. PostProcessRenderPipeline.prototype._rebuild = function () {
  76997. };
  76998. /** @hidden */
  76999. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77000. var renderEffects = this._renderEffects[renderEffectName];
  77001. if (!renderEffects) {
  77002. return;
  77003. }
  77004. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77005. };
  77006. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77007. var renderEffects = this._renderEffects[renderEffectName];
  77008. if (!renderEffects) {
  77009. return;
  77010. }
  77011. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77012. };
  77013. /** @hidden */
  77014. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77015. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77016. if (!cams) {
  77017. return;
  77018. }
  77019. var indicesToDelete = [];
  77020. var i;
  77021. for (i = 0; i < cams.length; i++) {
  77022. var camera = cams[i];
  77023. var cameraName = camera.name;
  77024. if (this._cameras.indexOf(camera) === -1) {
  77025. this._cameras[cameraName] = camera;
  77026. }
  77027. else if (unique) {
  77028. indicesToDelete.push(i);
  77029. }
  77030. }
  77031. for (i = 0; i < indicesToDelete.length; i++) {
  77032. cameras.splice(indicesToDelete[i], 1);
  77033. }
  77034. for (var renderEffectName in this._renderEffects) {
  77035. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77036. this._renderEffects[renderEffectName]._attachCameras(cams);
  77037. }
  77038. }
  77039. };
  77040. /** @hidden */
  77041. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77042. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77043. if (!cams) {
  77044. return;
  77045. }
  77046. for (var renderEffectName in this._renderEffects) {
  77047. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77048. this._renderEffects[renderEffectName]._detachCameras(cams);
  77049. }
  77050. }
  77051. for (var i = 0; i < cams.length; i++) {
  77052. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77053. }
  77054. };
  77055. /** @hidden */
  77056. PostProcessRenderPipeline.prototype._update = function () {
  77057. for (var renderEffectName in this._renderEffects) {
  77058. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77059. this._renderEffects[renderEffectName]._update();
  77060. }
  77061. }
  77062. for (var i = 0; i < this._cameras.length; i++) {
  77063. var cameraName = this._cameras[i].name;
  77064. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77065. this._renderEffectsForIsolatedPass[cameraName]._update();
  77066. }
  77067. }
  77068. };
  77069. /** @hidden */
  77070. PostProcessRenderPipeline.prototype._reset = function () {
  77071. this._renderEffects = {};
  77072. this._renderEffectsForIsolatedPass = new Array();
  77073. };
  77074. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77075. // 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)
  77076. var effectKeys = Object.keys(this._renderEffects);
  77077. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77078. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77079. if (postProcesses) {
  77080. postProcesses[0].samples = sampleCount;
  77081. return true;
  77082. }
  77083. }
  77084. return false;
  77085. };
  77086. PostProcessRenderPipeline.prototype.dispose = function () {
  77087. // Must be implemented by children
  77088. };
  77089. __decorate([
  77090. BABYLON.serialize()
  77091. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77092. return PostProcessRenderPipeline;
  77093. }());
  77094. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77095. })(BABYLON || (BABYLON = {}));
  77096. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77097. var BABYLON;
  77098. (function (BABYLON) {
  77099. /**
  77100. * This represents a depth renderer in Babylon.
  77101. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77102. */
  77103. var DepthRenderer = /** @class */ (function () {
  77104. /**
  77105. * Instantiates a depth renderer
  77106. * @param scene The scene the renderer belongs to
  77107. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77108. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77109. */
  77110. function DepthRenderer(scene, type, camera) {
  77111. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77112. if (camera === void 0) { camera = null; }
  77113. var _this = this;
  77114. this._scene = scene;
  77115. // Register the G Buffer component to the scene.
  77116. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77117. if (!component) {
  77118. component = new BABYLON.DepthRendererSceneComponent(scene);
  77119. scene._addComponent(component);
  77120. }
  77121. this._camera = camera;
  77122. var engine = scene.getEngine();
  77123. // Render target
  77124. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77125. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77126. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77127. this._depthMap.refreshRate = 1;
  77128. this._depthMap.renderParticles = false;
  77129. this._depthMap.renderList = null;
  77130. // Camera to get depth map from to support multiple concurrent cameras
  77131. this._depthMap.activeCamera = this._camera;
  77132. this._depthMap.ignoreCameraViewport = true;
  77133. this._depthMap.useCameraPostProcesses = false;
  77134. // set default depth value to 1.0 (far away)
  77135. this._depthMap.onClearObservable.add(function (engine) {
  77136. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77137. });
  77138. // Custom render function
  77139. var renderSubMesh = function (subMesh) {
  77140. var mesh = subMesh.getRenderingMesh();
  77141. var scene = _this._scene;
  77142. var engine = scene.getEngine();
  77143. var material = subMesh.getMaterial();
  77144. if (!material) {
  77145. return;
  77146. }
  77147. // Culling and reverse (right handed system)
  77148. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77149. // Managing instances
  77150. var batch = mesh._getInstancesRenderList(subMesh._id);
  77151. if (batch.mustReturn) {
  77152. return;
  77153. }
  77154. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77155. var camera = _this._camera || scene.activeCamera;
  77156. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77157. engine.enableEffect(_this._effect);
  77158. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77159. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77160. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77161. // Alpha test
  77162. if (material && material.needAlphaTesting()) {
  77163. var alphaTexture = material.getAlphaTestTexture();
  77164. if (alphaTexture) {
  77165. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77166. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77167. }
  77168. }
  77169. // Bones
  77170. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77171. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77172. }
  77173. // Draw
  77174. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77175. }
  77176. };
  77177. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77178. var index;
  77179. if (depthOnlySubMeshes.length) {
  77180. engine.setColorWrite(false);
  77181. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77182. renderSubMesh(depthOnlySubMeshes.data[index]);
  77183. }
  77184. engine.setColorWrite(true);
  77185. }
  77186. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77187. renderSubMesh(opaqueSubMeshes.data[index]);
  77188. }
  77189. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77190. renderSubMesh(alphaTestSubMeshes.data[index]);
  77191. }
  77192. };
  77193. }
  77194. /**
  77195. * Creates the depth rendering effect and checks if the effect is ready.
  77196. * @param subMesh The submesh to be used to render the depth map of
  77197. * @param useInstances If multiple world instances should be used
  77198. * @returns if the depth renderer is ready to render the depth map
  77199. */
  77200. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77201. var material = subMesh.getMaterial();
  77202. if (material.disableDepthWrite) {
  77203. return false;
  77204. }
  77205. var defines = [];
  77206. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77207. var mesh = subMesh.getMesh();
  77208. // Alpha test
  77209. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77210. defines.push("#define ALPHATEST");
  77211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77212. attribs.push(BABYLON.VertexBuffer.UVKind);
  77213. defines.push("#define UV1");
  77214. }
  77215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77216. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77217. defines.push("#define UV2");
  77218. }
  77219. }
  77220. // Bones
  77221. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77224. if (mesh.numBoneInfluencers > 4) {
  77225. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77226. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77227. }
  77228. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77229. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77230. }
  77231. else {
  77232. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77233. }
  77234. // Instances
  77235. if (useInstances) {
  77236. defines.push("#define INSTANCES");
  77237. attribs.push("world0");
  77238. attribs.push("world1");
  77239. attribs.push("world2");
  77240. attribs.push("world3");
  77241. }
  77242. // Get correct effect
  77243. var join = defines.join("\n");
  77244. if (this._cachedDefines !== join) {
  77245. this._cachedDefines = join;
  77246. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  77247. }
  77248. return this._effect.isReady();
  77249. };
  77250. /**
  77251. * Gets the texture which the depth map will be written to.
  77252. * @returns The depth map texture
  77253. */
  77254. DepthRenderer.prototype.getDepthMap = function () {
  77255. return this._depthMap;
  77256. };
  77257. /**
  77258. * Disposes of the depth renderer.
  77259. */
  77260. DepthRenderer.prototype.dispose = function () {
  77261. this._depthMap.dispose();
  77262. };
  77263. return DepthRenderer;
  77264. }());
  77265. BABYLON.DepthRenderer = DepthRenderer;
  77266. })(BABYLON || (BABYLON = {}));
  77267. //# sourceMappingURL=babylon.depthRenderer.js.map
  77268. var BABYLON;
  77269. (function (BABYLON) {
  77270. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  77271. camera = camera || this.activeCamera;
  77272. if (!camera) {
  77273. throw "No camera available to enable depth renderer";
  77274. }
  77275. if (!this._depthRenderer) {
  77276. this._depthRenderer = {};
  77277. }
  77278. if (!this._depthRenderer[camera.id]) {
  77279. var textureType = 0;
  77280. if (this.getEngine().getCaps().textureHalfFloatRender) {
  77281. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77282. }
  77283. else if (this.getEngine().getCaps().textureFloatRender) {
  77284. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77285. }
  77286. else {
  77287. throw "Depth renderer does not support int texture type";
  77288. }
  77289. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  77290. }
  77291. return this._depthRenderer[camera.id];
  77292. };
  77293. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  77294. camera = camera || this.activeCamera;
  77295. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  77296. return;
  77297. }
  77298. this._depthRenderer[camera.id].dispose();
  77299. delete this._depthRenderer[camera.id];
  77300. };
  77301. /**
  77302. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  77303. * in several rendering techniques.
  77304. */
  77305. var DepthRendererSceneComponent = /** @class */ (function () {
  77306. /**
  77307. * Creates a new instance of the component for the given scene
  77308. * @param scene Defines the scene to register the component in
  77309. */
  77310. function DepthRendererSceneComponent(scene) {
  77311. /**
  77312. * The component name helpfull to identify the component in the list of scene components.
  77313. */
  77314. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  77315. this.scene = scene;
  77316. }
  77317. /**
  77318. * Registers the component in a given scene
  77319. */
  77320. DepthRendererSceneComponent.prototype.register = function () {
  77321. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  77322. };
  77323. /**
  77324. * Rebuilds the elements related to this component in case of
  77325. * context lost for instance.
  77326. */
  77327. DepthRendererSceneComponent.prototype.rebuild = function () {
  77328. // Nothing to do for this component
  77329. };
  77330. /**
  77331. * Disposes the component and the associated ressources
  77332. */
  77333. DepthRendererSceneComponent.prototype.dispose = function () {
  77334. for (var key in this.scene._depthRenderer) {
  77335. this.scene._depthRenderer[key].dispose();
  77336. }
  77337. };
  77338. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77339. if (this.scene._depthRenderer) {
  77340. for (var key in this.scene._depthRenderer) {
  77341. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  77342. }
  77343. }
  77344. };
  77345. return DepthRendererSceneComponent;
  77346. }());
  77347. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  77348. })(BABYLON || (BABYLON = {}));
  77349. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  77350. var BABYLON;
  77351. (function (BABYLON) {
  77352. /**
  77353. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77354. */
  77355. var GeometryBufferRenderer = /** @class */ (function () {
  77356. /**
  77357. * Creates a new G Buffer for the scene
  77358. * @param scene The scene the buffer belongs to
  77359. * @param ratio How big is the buffer related to the main canvas.
  77360. */
  77361. function GeometryBufferRenderer(scene, ratio) {
  77362. if (ratio === void 0) { ratio = 1; }
  77363. this._enablePosition = false;
  77364. this._scene = scene;
  77365. this._ratio = ratio;
  77366. // Register the G Buffer component to the scene.
  77367. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  77368. if (!component) {
  77369. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  77370. scene._addComponent(component);
  77371. }
  77372. // Render target
  77373. this._createRenderTargets();
  77374. }
  77375. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77376. /**
  77377. * Set the render list (meshes to be rendered) used in the G buffer.
  77378. */
  77379. set: function (meshes) {
  77380. this._multiRenderTarget.renderList = meshes;
  77381. },
  77382. enumerable: true,
  77383. configurable: true
  77384. });
  77385. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77386. /**
  77387. * Gets wether or not G buffer are supported by the running hardware.
  77388. * This requires draw buffer supports
  77389. */
  77390. get: function () {
  77391. return this._multiRenderTarget.isSupported;
  77392. },
  77393. enumerable: true,
  77394. configurable: true
  77395. });
  77396. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77397. /**
  77398. * Gets wether or not position are enabled for the G buffer.
  77399. */
  77400. get: function () {
  77401. return this._enablePosition;
  77402. },
  77403. /**
  77404. * Sets wether or not position are enabled for the G buffer.
  77405. */
  77406. set: function (enable) {
  77407. this._enablePosition = enable;
  77408. this.dispose();
  77409. this._createRenderTargets();
  77410. },
  77411. enumerable: true,
  77412. configurable: true
  77413. });
  77414. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77415. /**
  77416. * Gets the scene associated with the buffer.
  77417. */
  77418. get: function () {
  77419. return this._scene;
  77420. },
  77421. enumerable: true,
  77422. configurable: true
  77423. });
  77424. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77425. /**
  77426. * Gets the ratio used by the buffer during its creation.
  77427. * How big is the buffer related to the main canvas.
  77428. */
  77429. get: function () {
  77430. return this._ratio;
  77431. },
  77432. enumerable: true,
  77433. configurable: true
  77434. });
  77435. /**
  77436. * Checks wether everything is ready to render a submesh to the G buffer.
  77437. * @param subMesh the submesh to check readiness for
  77438. * @param useInstances is the mesh drawn using instance or not
  77439. * @returns true if ready otherwise false
  77440. */
  77441. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77442. var material = subMesh.getMaterial();
  77443. if (material && material.disableDepthWrite) {
  77444. return false;
  77445. }
  77446. var defines = [];
  77447. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77448. var mesh = subMesh.getMesh();
  77449. // Alpha test
  77450. if (material && material.needAlphaTesting()) {
  77451. defines.push("#define ALPHATEST");
  77452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77453. attribs.push(BABYLON.VertexBuffer.UVKind);
  77454. defines.push("#define UV1");
  77455. }
  77456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77457. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77458. defines.push("#define UV2");
  77459. }
  77460. }
  77461. // Buffers
  77462. if (this._enablePosition) {
  77463. defines.push("#define POSITION");
  77464. }
  77465. // Bones
  77466. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77469. if (mesh.numBoneInfluencers > 4) {
  77470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77472. }
  77473. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77474. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77475. }
  77476. else {
  77477. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77478. }
  77479. // Instances
  77480. if (useInstances) {
  77481. defines.push("#define INSTANCES");
  77482. attribs.push("world0");
  77483. attribs.push("world1");
  77484. attribs.push("world2");
  77485. attribs.push("world3");
  77486. }
  77487. // Get correct effect
  77488. var join = defines.join("\n");
  77489. if (this._cachedDefines !== join) {
  77490. this._cachedDefines = join;
  77491. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77492. }
  77493. return this._effect.isReady();
  77494. };
  77495. /**
  77496. * Gets the current underlying G Buffer.
  77497. * @returns the buffer
  77498. */
  77499. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77500. return this._multiRenderTarget;
  77501. };
  77502. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77503. /**
  77504. * Gets the number of samples used to render the buffer (anti aliasing).
  77505. */
  77506. get: function () {
  77507. return this._multiRenderTarget.samples;
  77508. },
  77509. /**
  77510. * Sets the number of samples used to render the buffer (anti aliasing).
  77511. */
  77512. set: function (value) {
  77513. this._multiRenderTarget.samples = value;
  77514. },
  77515. enumerable: true,
  77516. configurable: true
  77517. });
  77518. /**
  77519. * Disposes the renderer and frees up associated resources.
  77520. */
  77521. GeometryBufferRenderer.prototype.dispose = function () {
  77522. this.getGBuffer().dispose();
  77523. };
  77524. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77525. var _this = this;
  77526. var engine = this._scene.getEngine();
  77527. var count = this._enablePosition ? 3 : 2;
  77528. 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 });
  77529. if (!this.isSupported) {
  77530. return;
  77531. }
  77532. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77533. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77534. this._multiRenderTarget.refreshRate = 1;
  77535. this._multiRenderTarget.renderParticles = false;
  77536. this._multiRenderTarget.renderList = null;
  77537. // set default depth value to 1.0 (far away)
  77538. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77539. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77540. });
  77541. // Custom render function
  77542. var renderSubMesh = function (subMesh) {
  77543. var mesh = subMesh.getRenderingMesh();
  77544. var scene = _this._scene;
  77545. var engine = scene.getEngine();
  77546. var material = subMesh.getMaterial();
  77547. if (!material) {
  77548. return;
  77549. }
  77550. // Culling
  77551. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77552. // Managing instances
  77553. var batch = mesh._getInstancesRenderList(subMesh._id);
  77554. if (batch.mustReturn) {
  77555. return;
  77556. }
  77557. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77558. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77559. engine.enableEffect(_this._effect);
  77560. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77561. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77562. _this._effect.setMatrix("view", scene.getViewMatrix());
  77563. // Alpha test
  77564. if (material && material.needAlphaTesting()) {
  77565. var alphaTexture = material.getAlphaTestTexture();
  77566. if (alphaTexture) {
  77567. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77568. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77569. }
  77570. }
  77571. // Bones
  77572. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77573. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77574. }
  77575. // Draw
  77576. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77577. }
  77578. };
  77579. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77580. var index;
  77581. if (depthOnlySubMeshes.length) {
  77582. engine.setColorWrite(false);
  77583. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77584. renderSubMesh(depthOnlySubMeshes.data[index]);
  77585. }
  77586. engine.setColorWrite(true);
  77587. }
  77588. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77589. renderSubMesh(opaqueSubMeshes.data[index]);
  77590. }
  77591. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77592. renderSubMesh(alphaTestSubMeshes.data[index]);
  77593. }
  77594. };
  77595. };
  77596. return GeometryBufferRenderer;
  77597. }());
  77598. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77599. })(BABYLON || (BABYLON = {}));
  77600. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77601. var BABYLON;
  77602. (function (BABYLON) {
  77603. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  77604. get: function () {
  77605. this._geometryBufferRenderer;
  77606. },
  77607. set: function (value) {
  77608. if (value && value.isSupported) {
  77609. this._geometryBufferRenderer = value;
  77610. }
  77611. ;
  77612. },
  77613. enumerable: true,
  77614. configurable: true
  77615. });
  77616. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  77617. if (ratio === void 0) { ratio = 1; }
  77618. if (this._geometryBufferRenderer) {
  77619. return this._geometryBufferRenderer;
  77620. }
  77621. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  77622. if (!this._geometryBufferRenderer.isSupported) {
  77623. this._geometryBufferRenderer = null;
  77624. }
  77625. return this._geometryBufferRenderer;
  77626. };
  77627. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  77628. if (!this._geometryBufferRenderer) {
  77629. return;
  77630. }
  77631. this._geometryBufferRenderer.dispose();
  77632. this._geometryBufferRenderer = null;
  77633. };
  77634. /**
  77635. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  77636. * in several rendering techniques.
  77637. */
  77638. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  77639. /**
  77640. * Creates a new instance of the component for the given scene
  77641. * @param scene Defines the scene to register the component in
  77642. */
  77643. function GeometryBufferRendererSceneComponent(scene) {
  77644. /**
  77645. * The component name helpfull to identify the component in the list of scene components.
  77646. */
  77647. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  77648. this.scene = scene;
  77649. }
  77650. /**
  77651. * Registers the component in a given scene
  77652. */
  77653. GeometryBufferRendererSceneComponent.prototype.register = function () {
  77654. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  77655. };
  77656. /**
  77657. * Rebuilds the elements related to this component in case of
  77658. * context lost for instance.
  77659. */
  77660. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  77661. // Nothing to do for this component
  77662. };
  77663. /**
  77664. * Disposes the component and the associated ressources
  77665. */
  77666. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  77667. // Nothing to do for this component
  77668. };
  77669. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77670. if (this.scene._geometryBufferRenderer) {
  77671. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  77672. }
  77673. };
  77674. return GeometryBufferRendererSceneComponent;
  77675. }());
  77676. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  77677. })(BABYLON || (BABYLON = {}));
  77678. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  77679. var BABYLON;
  77680. (function (BABYLON) {
  77681. var SSAORenderingPipeline = /** @class */ (function (_super) {
  77682. __extends(SSAORenderingPipeline, _super);
  77683. /**
  77684. * @constructor
  77685. * @param {string} name - The rendering pipeline name
  77686. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77687. * @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 }
  77688. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77689. */
  77690. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77691. var _this = _super.call(this, scene.getEngine(), name) || this;
  77692. // Members
  77693. /**
  77694. * The PassPostProcess id in the pipeline that contains the original scene color
  77695. */
  77696. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77697. /**
  77698. * The SSAO PostProcess id in the pipeline
  77699. */
  77700. _this.SSAORenderEffect = "SSAORenderEffect";
  77701. /**
  77702. * The horizontal blur PostProcess id in the pipeline
  77703. */
  77704. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77705. /**
  77706. * The vertical blur PostProcess id in the pipeline
  77707. */
  77708. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77709. /**
  77710. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77711. */
  77712. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77713. /**
  77714. * The output strength of the SSAO post-process. Default value is 1.0.
  77715. */
  77716. _this.totalStrength = 1.0;
  77717. /**
  77718. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77719. */
  77720. _this.radius = 0.0001;
  77721. /**
  77722. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77723. * Must not be equal to fallOff and superior to fallOff.
  77724. * Default value is 0.975
  77725. */
  77726. _this.area = 0.0075;
  77727. /**
  77728. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77729. * Must not be equal to area and inferior to area.
  77730. * Default value is 0.0
  77731. */
  77732. _this.fallOff = 0.000001;
  77733. /**
  77734. * The base color of the SSAO post-process
  77735. * The final result is "base + ssao" between [0, 1]
  77736. */
  77737. _this.base = 0.5;
  77738. _this._firstUpdate = true;
  77739. _this._scene = scene;
  77740. // Set up assets
  77741. _this._createRandomTexture();
  77742. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77743. var ssaoRatio = ratio.ssaoRatio || ratio;
  77744. var combineRatio = ratio.combineRatio || ratio;
  77745. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77746. _this._createSSAOPostProcess(ssaoRatio);
  77747. _this._createBlurPostProcess(ssaoRatio);
  77748. _this._createSSAOCombinePostProcess(combineRatio);
  77749. // Set up pipeline
  77750. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77751. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77752. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77753. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77754. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77755. // Finish
  77756. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77757. if (cameras)
  77758. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77759. return _this;
  77760. }
  77761. // Public Methods
  77762. /**
  77763. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77764. */
  77765. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77766. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77767. for (var i = 0; i < this._scene.cameras.length; i++) {
  77768. var camera = this._scene.cameras[i];
  77769. this._originalColorPostProcess.dispose(camera);
  77770. this._ssaoPostProcess.dispose(camera);
  77771. this._blurHPostProcess.dispose(camera);
  77772. this._blurVPostProcess.dispose(camera);
  77773. this._ssaoCombinePostProcess.dispose(camera);
  77774. }
  77775. this._randomTexture.dispose();
  77776. if (disableDepthRender)
  77777. this._scene.disableDepthRenderer();
  77778. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77779. _super.prototype.dispose.call(this);
  77780. };
  77781. // Private Methods
  77782. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77783. var _this = this;
  77784. var size = 16;
  77785. 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);
  77786. 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);
  77787. this._blurHPostProcess.onActivateObservable.add(function () {
  77788. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77789. _this._blurHPostProcess.kernel = size * dw;
  77790. });
  77791. this._blurVPostProcess.onActivateObservable.add(function () {
  77792. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77793. _this._blurVPostProcess.kernel = size * dw;
  77794. });
  77795. };
  77796. /** @hidden */
  77797. SSAORenderingPipeline.prototype._rebuild = function () {
  77798. this._firstUpdate = true;
  77799. _super.prototype._rebuild.call(this);
  77800. };
  77801. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77802. var _this = this;
  77803. var numSamples = 16;
  77804. var sampleSphere = [
  77805. 0.5381, 0.1856, -0.4319,
  77806. 0.1379, 0.2486, 0.4430,
  77807. 0.3371, 0.5679, -0.0057,
  77808. -0.6999, -0.0451, -0.0019,
  77809. 0.0689, -0.1598, -0.8547,
  77810. 0.0560, 0.0069, -0.1843,
  77811. -0.0146, 0.1402, 0.0762,
  77812. 0.0100, -0.1924, -0.0344,
  77813. -0.3577, -0.5301, -0.4358,
  77814. -0.3169, 0.1063, 0.0158,
  77815. 0.0103, -0.5869, 0.0046,
  77816. -0.0897, -0.4940, 0.3287,
  77817. 0.7119, -0.0154, -0.0918,
  77818. -0.0533, 0.0596, -0.5411,
  77819. 0.0352, -0.0631, 0.5460,
  77820. -0.4776, 0.2847, -0.0271
  77821. ];
  77822. var samplesFactor = 1.0 / numSamples;
  77823. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77824. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77825. "area", "fallOff", "base", "range", "viewport"
  77826. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77827. this._ssaoPostProcess.onApply = function (effect) {
  77828. if (_this._firstUpdate) {
  77829. effect.setArray3("sampleSphere", sampleSphere);
  77830. effect.setFloat("samplesFactor", samplesFactor);
  77831. effect.setFloat("randTextureTiles", 4.0);
  77832. }
  77833. effect.setFloat("totalStrength", _this.totalStrength);
  77834. effect.setFloat("radius", _this.radius);
  77835. effect.setFloat("area", _this.area);
  77836. effect.setFloat("fallOff", _this.fallOff);
  77837. effect.setFloat("base", _this.base);
  77838. effect.setTexture("textureSampler", _this._depthTexture);
  77839. effect.setTexture("randomSampler", _this._randomTexture);
  77840. };
  77841. };
  77842. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77843. var _this = this;
  77844. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77845. this._ssaoCombinePostProcess.onApply = function (effect) {
  77846. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77847. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77848. };
  77849. };
  77850. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77851. var size = 512;
  77852. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77853. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77854. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77855. var context = this._randomTexture.getContext();
  77856. var rand = function (min, max) {
  77857. return Math.random() * (max - min) + min;
  77858. };
  77859. var randVector = BABYLON.Vector3.Zero();
  77860. for (var x = 0; x < size; x++) {
  77861. for (var y = 0; y < size; y++) {
  77862. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77863. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77864. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77865. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77866. context.fillRect(x, y, 1, 1);
  77867. }
  77868. }
  77869. this._randomTexture.update(false);
  77870. };
  77871. __decorate([
  77872. BABYLON.serialize()
  77873. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77874. __decorate([
  77875. BABYLON.serialize()
  77876. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77877. __decorate([
  77878. BABYLON.serialize()
  77879. ], SSAORenderingPipeline.prototype, "area", void 0);
  77880. __decorate([
  77881. BABYLON.serialize()
  77882. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77883. __decorate([
  77884. BABYLON.serialize()
  77885. ], SSAORenderingPipeline.prototype, "base", void 0);
  77886. return SSAORenderingPipeline;
  77887. }(BABYLON.PostProcessRenderPipeline));
  77888. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77889. })(BABYLON || (BABYLON = {}));
  77890. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77891. var BABYLON;
  77892. (function (BABYLON) {
  77893. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77894. __extends(SSAO2RenderingPipeline, _super);
  77895. /**
  77896. * @constructor
  77897. * @param {string} name - The rendering pipeline name
  77898. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77899. * @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 }
  77900. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77901. */
  77902. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77903. var _this = _super.call(this, scene.getEngine(), name) || this;
  77904. // Members
  77905. /**
  77906. * The PassPostProcess id in the pipeline that contains the original scene color
  77907. */
  77908. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77909. /**
  77910. * The SSAO PostProcess id in the pipeline
  77911. */
  77912. _this.SSAORenderEffect = "SSAORenderEffect";
  77913. /**
  77914. * The horizontal blur PostProcess id in the pipeline
  77915. */
  77916. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77917. /**
  77918. * The vertical blur PostProcess id in the pipeline
  77919. */
  77920. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77921. /**
  77922. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77923. */
  77924. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77925. /**
  77926. * The output strength of the SSAO post-process. Default value is 1.0.
  77927. */
  77928. _this.totalStrength = 1.0;
  77929. /**
  77930. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77931. */
  77932. _this.maxZ = 100.0;
  77933. /**
  77934. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77935. */
  77936. _this.minZAspect = 0.2;
  77937. _this._samples = 8;
  77938. _this._textureSamples = 1;
  77939. /**
  77940. * Are we using bilateral blur ?
  77941. */
  77942. _this._expensiveBlur = true;
  77943. /**
  77944. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77945. */
  77946. _this.radius = 2.0;
  77947. /**
  77948. * The base color of the SSAO post-process
  77949. * The final result is "base + ssao" between [0, 1]
  77950. */
  77951. _this.base = 0;
  77952. _this._firstUpdate = true;
  77953. _this._bits = new Uint32Array(1);
  77954. _this._scene = scene;
  77955. _this._ratio = ratio;
  77956. if (!_this.isSupported) {
  77957. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77958. return _this;
  77959. }
  77960. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77961. var blurRatio = _this._ratio.blurRatio || ratio;
  77962. // Set up assets
  77963. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77964. _this._createRandomTexture();
  77965. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77966. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77967. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77968. _this._originalColorPostProcess.samples = _this.textureSamples;
  77969. _this._createSSAOPostProcess(1.0);
  77970. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77971. _this._createSSAOCombinePostProcess(blurRatio);
  77972. // Set up pipeline
  77973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77978. // Finish
  77979. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77980. if (cameras)
  77981. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77982. return _this;
  77983. }
  77984. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77985. get: function () {
  77986. return this._samples;
  77987. },
  77988. /**
  77989. * Number of samples used for the SSAO calculations. Default value is 8
  77990. */
  77991. set: function (n) {
  77992. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77993. this._samples = n;
  77994. this._sampleSphere = this._generateHemisphere();
  77995. this._firstUpdate = true;
  77996. },
  77997. enumerable: true,
  77998. configurable: true
  77999. });
  78000. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78001. get: function () {
  78002. return this._textureSamples;
  78003. },
  78004. /**
  78005. * Number of samples to use for antialiasing
  78006. */
  78007. set: function (n) {
  78008. this._textureSamples = n;
  78009. this._originalColorPostProcess.samples = n;
  78010. this._blurHPostProcess.samples = n;
  78011. this._blurVPostProcess.samples = n;
  78012. this._ssaoPostProcess.samples = n;
  78013. this._ssaoCombinePostProcess.samples = n;
  78014. },
  78015. enumerable: true,
  78016. configurable: true
  78017. });
  78018. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78019. get: function () {
  78020. return this._expensiveBlur;
  78021. },
  78022. set: function (b) {
  78023. 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"]);
  78024. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78025. this._expensiveBlur = b;
  78026. this._firstUpdate = true;
  78027. },
  78028. enumerable: true,
  78029. configurable: true
  78030. });
  78031. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78032. /**
  78033. * Support test.
  78034. */
  78035. get: function () {
  78036. var engine = BABYLON.Engine.LastCreatedEngine;
  78037. if (!engine) {
  78038. return false;
  78039. }
  78040. return engine.getCaps().drawBuffersExtension;
  78041. },
  78042. enumerable: true,
  78043. configurable: true
  78044. });
  78045. // Public Methods
  78046. /**
  78047. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78048. */
  78049. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78050. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78051. for (var i = 0; i < this._scene.cameras.length; i++) {
  78052. var camera = this._scene.cameras[i];
  78053. this._originalColorPostProcess.dispose(camera);
  78054. this._ssaoPostProcess.dispose(camera);
  78055. this._blurHPostProcess.dispose(camera);
  78056. this._blurVPostProcess.dispose(camera);
  78057. this._ssaoCombinePostProcess.dispose(camera);
  78058. }
  78059. this._randomTexture.dispose();
  78060. if (disableGeometryBufferRenderer)
  78061. this._scene.disableGeometryBufferRenderer();
  78062. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78063. _super.prototype.dispose.call(this);
  78064. };
  78065. // Private Methods
  78066. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78067. var _this = this;
  78068. this._samplerOffsets = [];
  78069. var expensive = this.expensiveBlur;
  78070. for (var i = -8; i < 8; i++) {
  78071. this._samplerOffsets.push(i * 2 + 0.5);
  78072. }
  78073. 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");
  78074. this._blurHPostProcess.onApply = function (effect) {
  78075. if (!_this._scene.activeCamera) {
  78076. return;
  78077. }
  78078. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78079. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78080. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78081. effect.setFloat("radius", _this.radius);
  78082. effect.setTexture("depthSampler", _this._depthTexture);
  78083. if (_this._firstUpdate) {
  78084. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78085. }
  78086. };
  78087. 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");
  78088. this._blurVPostProcess.onApply = function (effect) {
  78089. if (!_this._scene.activeCamera) {
  78090. return;
  78091. }
  78092. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78093. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78094. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78095. effect.setFloat("radius", _this.radius);
  78096. effect.setTexture("depthSampler", _this._depthTexture);
  78097. if (_this._firstUpdate) {
  78098. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78099. _this._firstUpdate = false;
  78100. }
  78101. };
  78102. this._blurHPostProcess.samples = this.textureSamples;
  78103. this._blurVPostProcess.samples = this.textureSamples;
  78104. };
  78105. /** @hidden */
  78106. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78107. this._firstUpdate = true;
  78108. _super.prototype._rebuild.call(this);
  78109. };
  78110. //Van der Corput radical inverse
  78111. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78112. this._bits[0] = i;
  78113. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78114. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78115. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78116. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78117. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78118. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78119. };
  78120. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78121. return [i / n, this._radicalInverse_VdC(i)];
  78122. };
  78123. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78124. var phi = v * 2.0 * Math.PI;
  78125. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78126. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78127. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78128. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78129. };
  78130. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78131. var numSamples = this.samples;
  78132. var result = [];
  78133. var vector;
  78134. var i = 0;
  78135. while (i < numSamples) {
  78136. if (numSamples < 16) {
  78137. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78138. }
  78139. else {
  78140. var rand = this._hammersley(i, numSamples);
  78141. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78142. }
  78143. result.push(vector.x, vector.y, vector.z);
  78144. i++;
  78145. }
  78146. return result;
  78147. };
  78148. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78149. var _this = this;
  78150. var numSamples = this.samples;
  78151. this._sampleSphere = this._generateHemisphere();
  78152. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78153. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78154. "base", "range", "projection", "near", "far", "texelSize",
  78155. "xViewport", "yViewport", "maxZ", "minZAspect"
  78156. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78157. this._ssaoPostProcess.onApply = function (effect) {
  78158. if (_this._firstUpdate) {
  78159. effect.setArray3("sampleSphere", _this._sampleSphere);
  78160. effect.setFloat("randTextureTiles", 32.0);
  78161. }
  78162. if (!_this._scene.activeCamera) {
  78163. return;
  78164. }
  78165. effect.setFloat("samplesFactor", 1 / _this.samples);
  78166. effect.setFloat("totalStrength", _this.totalStrength);
  78167. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78168. effect.setFloat("radius", _this.radius);
  78169. effect.setFloat("maxZ", _this.maxZ);
  78170. effect.setFloat("minZAspect", _this.minZAspect);
  78171. effect.setFloat("base", _this.base);
  78172. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78173. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78174. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78175. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78176. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78177. effect.setTexture("textureSampler", _this._depthTexture);
  78178. effect.setTexture("normalSampler", _this._normalTexture);
  78179. effect.setTexture("randomSampler", _this._randomTexture);
  78180. };
  78181. this._ssaoPostProcess.samples = this.textureSamples;
  78182. };
  78183. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78184. var _this = this;
  78185. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78186. this._ssaoCombinePostProcess.onApply = function (effect) {
  78187. var viewport = _this._scene.activeCamera.viewport;
  78188. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78189. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78190. };
  78191. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78192. };
  78193. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78194. var size = 128;
  78195. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78196. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78197. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78198. var context = this._randomTexture.getContext();
  78199. var rand = function (min, max) {
  78200. return Math.random() * (max - min) + min;
  78201. };
  78202. var randVector = BABYLON.Vector3.Zero();
  78203. for (var x = 0; x < size; x++) {
  78204. for (var y = 0; y < size; y++) {
  78205. randVector.x = rand(0.0, 1.0);
  78206. randVector.y = rand(0.0, 1.0);
  78207. randVector.z = 0.0;
  78208. randVector.normalize();
  78209. randVector.scaleInPlace(255);
  78210. randVector.x = Math.floor(randVector.x);
  78211. randVector.y = Math.floor(randVector.y);
  78212. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78213. context.fillRect(x, y, 1, 1);
  78214. }
  78215. }
  78216. this._randomTexture.update(false);
  78217. };
  78218. /**
  78219. * Serialize the rendering pipeline (Used when exporting)
  78220. * @returns the serialized object
  78221. */
  78222. SSAO2RenderingPipeline.prototype.serialize = function () {
  78223. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78224. serializationObject.customType = "SSAO2RenderingPipeline";
  78225. return serializationObject;
  78226. };
  78227. /**
  78228. * Parse the serialized pipeline
  78229. * @param source Source pipeline.
  78230. * @param scene The scene to load the pipeline to.
  78231. * @param rootUrl The URL of the serialized pipeline.
  78232. * @returns An instantiated pipeline from the serialized object.
  78233. */
  78234. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  78235. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78236. };
  78237. __decorate([
  78238. BABYLON.serialize()
  78239. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  78240. __decorate([
  78241. BABYLON.serialize()
  78242. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  78243. __decorate([
  78244. BABYLON.serialize()
  78245. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  78246. __decorate([
  78247. BABYLON.serialize("samples")
  78248. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  78249. __decorate([
  78250. BABYLON.serialize("textureSamples")
  78251. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  78252. __decorate([
  78253. BABYLON.serialize()
  78254. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  78255. __decorate([
  78256. BABYLON.serialize("expensiveBlur")
  78257. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  78258. __decorate([
  78259. BABYLON.serialize()
  78260. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  78261. __decorate([
  78262. BABYLON.serialize()
  78263. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  78264. return SSAO2RenderingPipeline;
  78265. }(BABYLON.PostProcessRenderPipeline));
  78266. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  78267. })(BABYLON || (BABYLON = {}));
  78268. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  78269. // BABYLON.JS Chromatic Aberration GLSL Shader
  78270. // Author: Olivier Guyot
  78271. // Separates very slightly R, G and B colors on the edges of the screen
  78272. // Inspired by Francois Tarlier & Martins Upitis
  78273. var BABYLON;
  78274. (function (BABYLON) {
  78275. var LensRenderingPipeline = /** @class */ (function (_super) {
  78276. __extends(LensRenderingPipeline, _super);
  78277. /**
  78278. * @constructor
  78279. *
  78280. * Effect parameters are as follow:
  78281. * {
  78282. * chromatic_aberration: number; // from 0 to x (1 for realism)
  78283. * edge_blur: number; // from 0 to x (1 for realism)
  78284. * distortion: number; // from 0 to x (1 for realism)
  78285. * grain_amount: number; // from 0 to 1
  78286. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  78287. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  78288. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  78289. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  78290. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  78291. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  78292. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  78293. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  78294. * }
  78295. * Note: if an effect parameter is unset, effect is disabled
  78296. *
  78297. * @param {string} name - The rendering pipeline name
  78298. * @param {object} parameters - An object containing all parameters (see above)
  78299. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78300. * @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)
  78301. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78302. */
  78303. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  78304. if (ratio === void 0) { ratio = 1.0; }
  78305. var _this = _super.call(this, scene.getEngine(), name) || this;
  78306. // Lens effects can be of the following:
  78307. // - chromatic aberration (slight shift of RGB colors)
  78308. // - blur on the edge of the lens
  78309. // - lens distortion
  78310. // - depth-of-field blur & highlights enhancing
  78311. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  78312. // - grain effect (noise or custom texture)
  78313. // Two additional texture samplers are needed:
  78314. // - depth map (for depth-of-field)
  78315. // - grain texture
  78316. /**
  78317. * The chromatic aberration PostProcess id in the pipeline
  78318. */
  78319. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  78320. /**
  78321. * The highlights enhancing PostProcess id in the pipeline
  78322. */
  78323. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  78324. /**
  78325. * The depth-of-field PostProcess id in the pipeline
  78326. */
  78327. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  78328. _this._scene = scene;
  78329. // Fetch texture samplers
  78330. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78331. if (parameters.grain_texture) {
  78332. _this._grainTexture = parameters.grain_texture;
  78333. }
  78334. else {
  78335. _this._createGrainTexture();
  78336. }
  78337. // save parameters
  78338. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  78339. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  78340. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  78341. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  78342. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  78343. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  78344. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  78345. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  78346. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  78347. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  78348. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  78349. // Create effects
  78350. _this._createChromaticAberrationPostProcess(ratio);
  78351. _this._createHighlightsPostProcess(ratio);
  78352. _this._createDepthOfFieldPostProcess(ratio / 4);
  78353. // Set up pipeline
  78354. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  78355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  78356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  78357. if (_this._highlightsGain === -1) {
  78358. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  78359. }
  78360. // Finish
  78361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78362. if (cameras) {
  78363. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78364. }
  78365. return _this;
  78366. }
  78367. // public methods (self explanatory)
  78368. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  78369. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  78370. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  78371. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  78372. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  78373. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  78374. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  78375. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  78376. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  78377. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  78378. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  78379. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  78380. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  78381. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  78382. };
  78383. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  78384. this._highlightsPostProcess.updateEffect();
  78385. };
  78386. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  78387. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  78388. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  78389. this._highlightsGain = amount;
  78390. };
  78391. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  78392. if (this._highlightsGain === -1) {
  78393. this._highlightsGain = 1.0;
  78394. }
  78395. this._highlightsThreshold = amount;
  78396. };
  78397. LensRenderingPipeline.prototype.disableHighlights = function () {
  78398. this._highlightsGain = -1;
  78399. };
  78400. /**
  78401. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  78402. */
  78403. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78404. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78405. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78406. this._chromaticAberrationPostProcess = null;
  78407. this._highlightsPostProcess = null;
  78408. this._depthOfFieldPostProcess = null;
  78409. this._grainTexture.dispose();
  78410. if (disableDepthRender)
  78411. this._scene.disableDepthRenderer();
  78412. };
  78413. // colors shifting and distortion
  78414. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  78415. var _this = this;
  78416. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  78417. [], // samplers
  78418. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78419. this._chromaticAberrationPostProcess.onApply = function (effect) {
  78420. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  78421. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78422. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78423. effect.setFloat('radialIntensity', 1);
  78424. effect.setFloat2('direction', 17, 17);
  78425. effect.setFloat2('centerPosition', 0.5, 0.5);
  78426. };
  78427. };
  78428. // highlights enhancing
  78429. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78430. var _this = this;
  78431. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78432. [], // samplers
  78433. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78434. this._highlightsPostProcess.onApply = function (effect) {
  78435. effect.setFloat('gain', _this._highlightsGain);
  78436. effect.setFloat('threshold', _this._highlightsThreshold);
  78437. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78438. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78439. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78440. };
  78441. };
  78442. // colors shifting and distortion
  78443. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  78444. var _this = this;
  78445. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  78446. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  78447. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  78448. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78449. this._depthOfFieldPostProcess.onApply = function (effect) {
  78450. effect.setTexture("depthSampler", _this._depthTexture);
  78451. effect.setTexture("grainSampler", _this._grainTexture);
  78452. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  78453. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  78454. effect.setFloat('grain_amount', _this._grainAmount);
  78455. effect.setBool('blur_noise', _this._blurNoise);
  78456. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78457. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78458. effect.setFloat('distortion', _this._distortion);
  78459. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78460. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78461. effect.setFloat('aperture', _this._dofAperture);
  78462. effect.setFloat('darken', _this._dofDarken);
  78463. effect.setFloat('edge_blur', _this._edgeBlur);
  78464. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78465. if (_this._scene.activeCamera) {
  78466. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78467. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78468. }
  78469. };
  78470. };
  78471. // creates a black and white random noise texture, 512x512
  78472. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78473. var size = 512;
  78474. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78475. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78476. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78477. var context = this._grainTexture.getContext();
  78478. var rand = function (min, max) {
  78479. return Math.random() * (max - min) + min;
  78480. };
  78481. var value;
  78482. for (var x = 0; x < size; x++) {
  78483. for (var y = 0; y < size; y++) {
  78484. value = Math.floor(rand(0.42, 0.58) * 255);
  78485. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78486. context.fillRect(x, y, 1, 1);
  78487. }
  78488. }
  78489. this._grainTexture.update(false);
  78490. };
  78491. return LensRenderingPipeline;
  78492. }(BABYLON.PostProcessRenderPipeline));
  78493. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78494. })(BABYLON || (BABYLON = {}));
  78495. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78496. var BABYLON;
  78497. (function (BABYLON) {
  78498. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78499. __extends(StandardRenderingPipeline, _super);
  78500. /**
  78501. * @constructor
  78502. * @param {string} name - The rendering pipeline name
  78503. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78504. * @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)
  78505. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  78506. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78507. */
  78508. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  78509. if (originalPostProcess === void 0) { originalPostProcess = null; }
  78510. var _this = _super.call(this, scene.getEngine(), name) || this;
  78511. _this.downSampleX4PostProcess = null;
  78512. _this.brightPassPostProcess = null;
  78513. _this.blurHPostProcesses = [];
  78514. _this.blurVPostProcesses = [];
  78515. _this.textureAdderPostProcess = null;
  78516. _this.volumetricLightPostProcess = null;
  78517. _this.volumetricLightSmoothXPostProcess = null;
  78518. _this.volumetricLightSmoothYPostProcess = null;
  78519. _this.volumetricLightMergePostProces = null;
  78520. _this.volumetricLightFinalPostProcess = null;
  78521. _this.luminancePostProcess = null;
  78522. _this.luminanceDownSamplePostProcesses = [];
  78523. _this.hdrPostProcess = null;
  78524. _this.textureAdderFinalPostProcess = null;
  78525. _this.lensFlareFinalPostProcess = null;
  78526. _this.hdrFinalPostProcess = null;
  78527. _this.lensFlarePostProcess = null;
  78528. _this.lensFlareComposePostProcess = null;
  78529. _this.motionBlurPostProcess = null;
  78530. _this.depthOfFieldPostProcess = null;
  78531. // Values
  78532. _this.brightThreshold = 1.0;
  78533. _this.blurWidth = 512.0;
  78534. _this.horizontalBlur = false;
  78535. _this.exposure = 1.0;
  78536. _this.lensTexture = null;
  78537. _this.volumetricLightCoefficient = 0.2;
  78538. _this.volumetricLightPower = 4.0;
  78539. _this.volumetricLightBlurScale = 64.0;
  78540. _this.sourceLight = null;
  78541. _this.hdrMinimumLuminance = 1.0;
  78542. _this.hdrDecreaseRate = 0.5;
  78543. _this.hdrIncreaseRate = 0.5;
  78544. _this.lensColorTexture = null;
  78545. _this.lensFlareStrength = 20.0;
  78546. _this.lensFlareGhostDispersal = 1.4;
  78547. _this.lensFlareHaloWidth = 0.7;
  78548. _this.lensFlareDistortionStrength = 16.0;
  78549. _this.lensStarTexture = null;
  78550. _this.lensFlareDirtTexture = null;
  78551. _this.depthOfFieldDistance = 10.0;
  78552. _this.depthOfFieldBlurWidth = 64.0;
  78553. _this.motionStrength = 1.0;
  78554. // IAnimatable
  78555. _this.animations = [];
  78556. _this._currentDepthOfFieldSource = null;
  78557. _this._hdrCurrentLuminance = 1.0;
  78558. // Getters and setters
  78559. _this._bloomEnabled = true;
  78560. _this._depthOfFieldEnabled = false;
  78561. _this._vlsEnabled = false;
  78562. _this._lensFlareEnabled = false;
  78563. _this._hdrEnabled = false;
  78564. _this._motionBlurEnabled = false;
  78565. _this._motionBlurSamples = 64.0;
  78566. _this._volumetricLightStepsCount = 50.0;
  78567. _this._cameras = cameras || [];
  78568. // Initialize
  78569. _this._scene = scene;
  78570. _this._basePostProcess = originalPostProcess;
  78571. _this._ratio = ratio;
  78572. // Misc
  78573. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78574. // Finish
  78575. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78576. _this._buildPipeline();
  78577. return _this;
  78578. }
  78579. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  78580. get: function () {
  78581. return this._bloomEnabled;
  78582. },
  78583. set: function (enabled) {
  78584. if (this._bloomEnabled === enabled) {
  78585. return;
  78586. }
  78587. this._bloomEnabled = enabled;
  78588. this._buildPipeline();
  78589. },
  78590. enumerable: true,
  78591. configurable: true
  78592. });
  78593. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  78594. get: function () {
  78595. return this._depthOfFieldEnabled;
  78596. },
  78597. set: function (enabled) {
  78598. if (this._depthOfFieldEnabled === enabled) {
  78599. return;
  78600. }
  78601. this._depthOfFieldEnabled = enabled;
  78602. this._buildPipeline();
  78603. },
  78604. enumerable: true,
  78605. configurable: true
  78606. });
  78607. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  78608. get: function () {
  78609. return this._lensFlareEnabled;
  78610. },
  78611. set: function (enabled) {
  78612. if (this._lensFlareEnabled === enabled) {
  78613. return;
  78614. }
  78615. this._lensFlareEnabled = enabled;
  78616. this._buildPipeline();
  78617. },
  78618. enumerable: true,
  78619. configurable: true
  78620. });
  78621. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  78622. get: function () {
  78623. return this._hdrEnabled;
  78624. },
  78625. set: function (enabled) {
  78626. if (this._hdrEnabled === enabled) {
  78627. return;
  78628. }
  78629. this._hdrEnabled = enabled;
  78630. this._buildPipeline();
  78631. },
  78632. enumerable: true,
  78633. configurable: true
  78634. });
  78635. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  78636. get: function () {
  78637. return this._vlsEnabled;
  78638. },
  78639. set: function (enabled) {
  78640. if (this._vlsEnabled === enabled) {
  78641. return;
  78642. }
  78643. if (enabled) {
  78644. var geometry = this._scene.enableGeometryBufferRenderer();
  78645. if (!geometry) {
  78646. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  78647. return;
  78648. }
  78649. }
  78650. this._vlsEnabled = enabled;
  78651. this._buildPipeline();
  78652. },
  78653. enumerable: true,
  78654. configurable: true
  78655. });
  78656. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  78657. get: function () {
  78658. return this._motionBlurEnabled;
  78659. },
  78660. set: function (enabled) {
  78661. if (this._motionBlurEnabled === enabled) {
  78662. return;
  78663. }
  78664. this._motionBlurEnabled = enabled;
  78665. this._buildPipeline();
  78666. },
  78667. enumerable: true,
  78668. configurable: true
  78669. });
  78670. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  78671. get: function () {
  78672. return this._volumetricLightStepsCount;
  78673. },
  78674. set: function (count) {
  78675. if (this.volumetricLightPostProcess) {
  78676. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  78677. }
  78678. this._volumetricLightStepsCount = count;
  78679. },
  78680. enumerable: true,
  78681. configurable: true
  78682. });
  78683. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  78684. get: function () {
  78685. return this._motionBlurSamples;
  78686. },
  78687. set: function (samples) {
  78688. if (this.motionBlurPostProcess) {
  78689. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78690. }
  78691. this._motionBlurSamples = samples;
  78692. },
  78693. enumerable: true,
  78694. configurable: true
  78695. });
  78696. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78697. var _this = this;
  78698. var ratio = this._ratio;
  78699. var scene = this._scene;
  78700. this._disposePostProcesses();
  78701. this._reset();
  78702. // Create pass post-process
  78703. if (!this._basePostProcess) {
  78704. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78705. this.originalPostProcess.onApply = function (effect) {
  78706. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78707. };
  78708. }
  78709. else {
  78710. this.originalPostProcess = this._basePostProcess;
  78711. }
  78712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78713. this._currentDepthOfFieldSource = this.originalPostProcess;
  78714. if (this._bloomEnabled) {
  78715. // Create down sample X4 post-process
  78716. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78717. // Create bright pass post-process
  78718. this._createBrightPassPostProcess(scene, ratio / 2);
  78719. // Create gaussian blur post-processes (down sampling blurs)
  78720. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78721. // Create texture adder post-process
  78722. this._createTextureAdderPostProcess(scene, ratio);
  78723. // Create depth-of-field source post-process
  78724. 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);
  78725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78726. }
  78727. if (this._vlsEnabled) {
  78728. // Create volumetric light
  78729. this._createVolumetricLightPostProcess(scene, ratio);
  78730. // Create volumetric light final post-process
  78731. 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);
  78732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78733. }
  78734. if (this._lensFlareEnabled) {
  78735. // Create lens flare post-process
  78736. this._createLensFlarePostProcess(scene, ratio);
  78737. // Create depth-of-field source post-process post lens-flare and disable it now
  78738. 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);
  78739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78740. }
  78741. if (this._hdrEnabled) {
  78742. // Create luminance
  78743. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78744. // Create HDR
  78745. this._createHdrPostProcess(scene, ratio);
  78746. // Create depth-of-field source post-process post hdr and disable it now
  78747. 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);
  78748. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78749. }
  78750. if (this._depthOfFieldEnabled) {
  78751. // Create gaussian blur used by depth-of-field
  78752. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78753. // Create depth-of-field post-process
  78754. this._createDepthOfFieldPostProcess(scene, ratio);
  78755. }
  78756. if (this._motionBlurEnabled) {
  78757. // Create motion blur post-process
  78758. this._createMotionBlurPostProcess(scene, ratio);
  78759. }
  78760. if (this._cameras !== null) {
  78761. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78762. }
  78763. };
  78764. // Down Sample X4 Post-Processs
  78765. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78766. var _this = this;
  78767. var downSampleX4Offsets = new Array(32);
  78768. 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);
  78769. this.downSampleX4PostProcess.onApply = function (effect) {
  78770. var id = 0;
  78771. var width = _this.downSampleX4PostProcess.width;
  78772. var height = _this.downSampleX4PostProcess.height;
  78773. for (var i = -2; i < 2; i++) {
  78774. for (var j = -2; j < 2; j++) {
  78775. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78776. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78777. id += 2;
  78778. }
  78779. }
  78780. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78781. };
  78782. // Add to pipeline
  78783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78784. };
  78785. // Brightpass Post-Process
  78786. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78787. var _this = this;
  78788. var brightOffsets = new Array(8);
  78789. 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);
  78790. this.brightPassPostProcess.onApply = function (effect) {
  78791. var sU = (1.0 / _this.brightPassPostProcess.width);
  78792. var sV = (1.0 / _this.brightPassPostProcess.height);
  78793. brightOffsets[0] = -0.5 * sU;
  78794. brightOffsets[1] = 0.5 * sV;
  78795. brightOffsets[2] = 0.5 * sU;
  78796. brightOffsets[3] = 0.5 * sV;
  78797. brightOffsets[4] = -0.5 * sU;
  78798. brightOffsets[5] = -0.5 * sV;
  78799. brightOffsets[6] = 0.5 * sU;
  78800. brightOffsets[7] = -0.5 * sV;
  78801. effect.setArray2("dsOffsets", brightOffsets);
  78802. effect.setFloat("brightThreshold", _this.brightThreshold);
  78803. };
  78804. // Add to pipeline
  78805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  78806. };
  78807. // Create blur H&V post-processes
  78808. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  78809. var _this = this;
  78810. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  78811. var engine = scene.getEngine();
  78812. 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);
  78813. 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);
  78814. blurX.onActivateObservable.add(function () {
  78815. var dw = blurX.width / engine.getRenderWidth();
  78816. blurX.kernel = _this[blurWidthKey] * dw;
  78817. });
  78818. blurY.onActivateObservable.add(function () {
  78819. var dw = blurY.height / engine.getRenderHeight();
  78820. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  78821. });
  78822. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  78823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  78824. this.blurHPostProcesses.push(blurX);
  78825. this.blurVPostProcesses.push(blurY);
  78826. };
  78827. // Create texture adder post-process
  78828. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  78829. var _this = this;
  78830. 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);
  78831. this.textureAdderPostProcess.onApply = function (effect) {
  78832. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  78833. effect.setTexture("lensSampler", _this.lensTexture);
  78834. effect.setFloat("exposure", _this.exposure);
  78835. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  78836. };
  78837. // Add to pipeline
  78838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  78839. };
  78840. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  78841. var _this = this;
  78842. var geometryRenderer = scene.enableGeometryBufferRenderer();
  78843. geometryRenderer.enablePosition = true;
  78844. var geometry = geometryRenderer.getGBuffer();
  78845. // Base post-process
  78846. 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));
  78847. var depthValues = BABYLON.Vector2.Zero();
  78848. this.volumetricLightPostProcess.onApply = function (effect) {
  78849. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  78850. var generator = _this.sourceLight.getShadowGenerator();
  78851. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  78852. effect.setTexture("positionSampler", geometry.textures[2]);
  78853. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  78854. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  78855. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  78856. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  78857. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  78858. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  78859. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  78860. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  78861. effect.setVector2("depthValues", depthValues);
  78862. }
  78863. };
  78864. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  78865. // Smooth
  78866. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  78867. // Merge
  78868. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  78869. this.volumetricLightMergePostProces.onApply = function (effect) {
  78870. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  78871. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  78872. };
  78873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  78874. };
  78875. // Create luminance
  78876. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  78877. var _this = this;
  78878. // Create luminance
  78879. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  78880. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  78881. var offsets = [];
  78882. this.luminancePostProcess.onApply = function (effect) {
  78883. var sU = (1.0 / _this.luminancePostProcess.width);
  78884. var sV = (1.0 / _this.luminancePostProcess.height);
  78885. offsets[0] = -0.5 * sU;
  78886. offsets[1] = 0.5 * sV;
  78887. offsets[2] = 0.5 * sU;
  78888. offsets[3] = 0.5 * sV;
  78889. offsets[4] = -0.5 * sU;
  78890. offsets[5] = -0.5 * sV;
  78891. offsets[6] = 0.5 * sU;
  78892. offsets[7] = -0.5 * sV;
  78893. effect.setArray2("lumOffsets", offsets);
  78894. };
  78895. // Add to pipeline
  78896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  78897. // Create down sample luminance
  78898. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  78899. var size = Math.pow(3, i);
  78900. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  78901. if (i === 0) {
  78902. defines += "#define FINAL_DOWN_SAMPLER";
  78903. }
  78904. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  78905. this.luminanceDownSamplePostProcesses.push(postProcess);
  78906. }
  78907. // Create callbacks and add effects
  78908. var lastLuminance = this.luminancePostProcess;
  78909. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  78910. var downSampleOffsets = new Array(18);
  78911. pp.onApply = function (effect) {
  78912. if (!lastLuminance) {
  78913. return;
  78914. }
  78915. var id = 0;
  78916. for (var x = -1; x < 2; x++) {
  78917. for (var y = -1; y < 2; y++) {
  78918. downSampleOffsets[id] = x / lastLuminance.width;
  78919. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78920. id += 2;
  78921. }
  78922. }
  78923. effect.setArray2("dsOffsets", downSampleOffsets);
  78924. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78925. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78926. lastLuminance = _this.luminancePostProcess;
  78927. }
  78928. else {
  78929. lastLuminance = pp;
  78930. }
  78931. };
  78932. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78933. pp.onAfterRender = function (effect) {
  78934. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78935. 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);
  78936. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78937. };
  78938. }
  78939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78940. });
  78941. };
  78942. // Create HDR post-process
  78943. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78944. var _this = this;
  78945. 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);
  78946. var outputLiminance = 1;
  78947. var time = 0;
  78948. var lastTime = 0;
  78949. this.hdrPostProcess.onApply = function (effect) {
  78950. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78951. time += scene.getEngine().getDeltaTime();
  78952. if (outputLiminance < 0) {
  78953. outputLiminance = _this._hdrCurrentLuminance;
  78954. }
  78955. else {
  78956. var dt = (lastTime - time) / 1000.0;
  78957. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78958. outputLiminance += _this.hdrDecreaseRate * dt;
  78959. }
  78960. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78961. outputLiminance -= _this.hdrIncreaseRate * dt;
  78962. }
  78963. else {
  78964. outputLiminance = _this._hdrCurrentLuminance;
  78965. }
  78966. }
  78967. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78968. effect.setFloat("averageLuminance", outputLiminance);
  78969. lastTime = time;
  78970. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78971. };
  78972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78973. };
  78974. // Create lens flare post-process
  78975. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78976. var _this = this;
  78977. 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);
  78978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78979. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78980. 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);
  78981. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78982. var resolution = new BABYLON.Vector2(0, 0);
  78983. // Lens flare
  78984. this.lensFlarePostProcess.onApply = function (effect) {
  78985. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78986. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78987. effect.setFloat("strength", _this.lensFlareStrength);
  78988. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78989. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78990. // Shift
  78991. resolution.x = _this.lensFlarePostProcess.width;
  78992. resolution.y = _this.lensFlarePostProcess.height;
  78993. effect.setVector2("resolution", resolution);
  78994. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78995. };
  78996. // Compose
  78997. 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);
  78998. 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);
  78999. this.lensFlareComposePostProcess.onApply = function (effect) {
  79000. if (!_this._scene.activeCamera) {
  79001. return;
  79002. }
  79003. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79004. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79005. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79006. // Lens start rotation matrix
  79007. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79008. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79009. 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));
  79010. camRot *= 4.0;
  79011. 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);
  79012. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  79013. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  79014. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  79015. };
  79016. };
  79017. // Create depth-of-field post-process
  79018. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  79019. var _this = this;
  79020. 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);
  79021. this.depthOfFieldPostProcess.onApply = function (effect) {
  79022. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79023. effect.setTexture("depthSampler", _this._getDepthTexture());
  79024. effect.setFloat("distance", _this.depthOfFieldDistance);
  79025. };
  79026. // Add to pipeline
  79027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  79028. };
  79029. // Create motion blur post-process
  79030. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  79031. var _this = this;
  79032. 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);
  79033. var motionScale = 0;
  79034. var prevViewProjection = BABYLON.Matrix.Identity();
  79035. var invViewProjection = BABYLON.Matrix.Identity();
  79036. var viewProjection = BABYLON.Matrix.Identity();
  79037. var screenSize = BABYLON.Vector2.Zero();
  79038. this.motionBlurPostProcess.onApply = function (effect) {
  79039. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  79040. viewProjection.invertToRef(invViewProjection);
  79041. effect.setMatrix("inverseViewProjection", invViewProjection);
  79042. effect.setMatrix("prevViewProjection", prevViewProjection);
  79043. prevViewProjection = viewProjection;
  79044. screenSize.x = _this.motionBlurPostProcess.width;
  79045. screenSize.y = _this.motionBlurPostProcess.height;
  79046. effect.setVector2("screenSize", screenSize);
  79047. motionScale = scene.getEngine().getFps() / 60.0;
  79048. effect.setFloat("motionScale", motionScale);
  79049. effect.setFloat("motionStrength", _this.motionStrength);
  79050. effect.setTexture("depthSampler", _this._getDepthTexture());
  79051. };
  79052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  79053. };
  79054. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  79055. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  79056. var renderer = this._scene.enableGeometryBufferRenderer();
  79057. return renderer.getGBuffer().textures[0];
  79058. }
  79059. return this._scene.enableDepthRenderer().getDepthMap();
  79060. };
  79061. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  79062. for (var i = 0; i < this._cameras.length; i++) {
  79063. var camera = this._cameras[i];
  79064. if (this.originalPostProcess) {
  79065. this.originalPostProcess.dispose(camera);
  79066. }
  79067. if (this.downSampleX4PostProcess) {
  79068. this.downSampleX4PostProcess.dispose(camera);
  79069. }
  79070. if (this.brightPassPostProcess) {
  79071. this.brightPassPostProcess.dispose(camera);
  79072. }
  79073. if (this.textureAdderPostProcess) {
  79074. this.textureAdderPostProcess.dispose(camera);
  79075. }
  79076. if (this.textureAdderFinalPostProcess) {
  79077. this.textureAdderFinalPostProcess.dispose(camera);
  79078. }
  79079. if (this.volumetricLightPostProcess) {
  79080. this.volumetricLightPostProcess.dispose(camera);
  79081. }
  79082. if (this.volumetricLightSmoothXPostProcess) {
  79083. this.volumetricLightSmoothXPostProcess.dispose(camera);
  79084. }
  79085. if (this.volumetricLightSmoothYPostProcess) {
  79086. this.volumetricLightSmoothYPostProcess.dispose(camera);
  79087. }
  79088. if (this.volumetricLightMergePostProces) {
  79089. this.volumetricLightMergePostProces.dispose(camera);
  79090. }
  79091. if (this.volumetricLightFinalPostProcess) {
  79092. this.volumetricLightFinalPostProcess.dispose(camera);
  79093. }
  79094. if (this.lensFlarePostProcess) {
  79095. this.lensFlarePostProcess.dispose(camera);
  79096. }
  79097. if (this.lensFlareComposePostProcess) {
  79098. this.lensFlareComposePostProcess.dispose(camera);
  79099. }
  79100. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  79101. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  79102. }
  79103. if (this.luminancePostProcess) {
  79104. this.luminancePostProcess.dispose(camera);
  79105. }
  79106. if (this.hdrPostProcess) {
  79107. this.hdrPostProcess.dispose(camera);
  79108. }
  79109. if (this.hdrFinalPostProcess) {
  79110. this.hdrFinalPostProcess.dispose(camera);
  79111. }
  79112. if (this.depthOfFieldPostProcess) {
  79113. this.depthOfFieldPostProcess.dispose(camera);
  79114. }
  79115. if (this.motionBlurPostProcess) {
  79116. this.motionBlurPostProcess.dispose(camera);
  79117. }
  79118. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  79119. this.blurHPostProcesses[j].dispose(camera);
  79120. }
  79121. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  79122. this.blurVPostProcesses[j].dispose(camera);
  79123. }
  79124. }
  79125. this.originalPostProcess = null;
  79126. this.downSampleX4PostProcess = null;
  79127. this.brightPassPostProcess = null;
  79128. this.textureAdderPostProcess = null;
  79129. this.textureAdderFinalPostProcess = null;
  79130. this.volumetricLightPostProcess = null;
  79131. this.volumetricLightSmoothXPostProcess = null;
  79132. this.volumetricLightSmoothYPostProcess = null;
  79133. this.volumetricLightMergePostProces = null;
  79134. this.volumetricLightFinalPostProcess = null;
  79135. this.lensFlarePostProcess = null;
  79136. this.lensFlareComposePostProcess = null;
  79137. this.luminancePostProcess = null;
  79138. this.hdrPostProcess = null;
  79139. this.hdrFinalPostProcess = null;
  79140. this.depthOfFieldPostProcess = null;
  79141. this.motionBlurPostProcess = null;
  79142. this.luminanceDownSamplePostProcesses = [];
  79143. this.blurHPostProcesses = [];
  79144. this.blurVPostProcesses = [];
  79145. };
  79146. /**
  79147. * Dispose of the pipeline and stop all post processes
  79148. */
  79149. StandardRenderingPipeline.prototype.dispose = function () {
  79150. this._disposePostProcesses();
  79151. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79152. _super.prototype.dispose.call(this);
  79153. };
  79154. /**
  79155. * Serialize the rendering pipeline (Used when exporting)
  79156. * @returns the serialized object
  79157. */
  79158. StandardRenderingPipeline.prototype.serialize = function () {
  79159. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79160. if (this.sourceLight) {
  79161. serializationObject.sourceLightId = this.sourceLight.id;
  79162. }
  79163. serializationObject.customType = "StandardRenderingPipeline";
  79164. return serializationObject;
  79165. };
  79166. /**
  79167. * Parse the serialized pipeline
  79168. * @param source Source pipeline.
  79169. * @param scene The scene to load the pipeline to.
  79170. * @param rootUrl The URL of the serialized pipeline.
  79171. * @returns An instantiated pipeline from the serialized object.
  79172. */
  79173. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79174. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79175. if (source.sourceLightId) {
  79176. p.sourceLight = scene.getLightByID(source.sourceLightId);
  79177. }
  79178. return p;
  79179. };
  79180. // Luminance steps
  79181. StandardRenderingPipeline.LuminanceSteps = 6;
  79182. __decorate([
  79183. BABYLON.serialize()
  79184. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  79185. __decorate([
  79186. BABYLON.serialize()
  79187. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  79188. __decorate([
  79189. BABYLON.serialize()
  79190. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  79191. __decorate([
  79192. BABYLON.serialize()
  79193. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  79194. __decorate([
  79195. BABYLON.serializeAsTexture("lensTexture")
  79196. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  79197. __decorate([
  79198. BABYLON.serialize()
  79199. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  79200. __decorate([
  79201. BABYLON.serialize()
  79202. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  79203. __decorate([
  79204. BABYLON.serialize()
  79205. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  79206. __decorate([
  79207. BABYLON.serialize()
  79208. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  79209. __decorate([
  79210. BABYLON.serialize()
  79211. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  79212. __decorate([
  79213. BABYLON.serialize()
  79214. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  79215. __decorate([
  79216. BABYLON.serializeAsTexture("lensColorTexture")
  79217. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  79218. __decorate([
  79219. BABYLON.serialize()
  79220. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  79221. __decorate([
  79222. BABYLON.serialize()
  79223. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  79224. __decorate([
  79225. BABYLON.serialize()
  79226. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  79227. __decorate([
  79228. BABYLON.serialize()
  79229. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  79230. __decorate([
  79231. BABYLON.serializeAsTexture("lensStarTexture")
  79232. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  79233. __decorate([
  79234. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  79235. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  79236. __decorate([
  79237. BABYLON.serialize()
  79238. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  79239. __decorate([
  79240. BABYLON.serialize()
  79241. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  79242. __decorate([
  79243. BABYLON.serialize()
  79244. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  79245. __decorate([
  79246. BABYLON.serialize()
  79247. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  79248. __decorate([
  79249. BABYLON.serialize()
  79250. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  79251. __decorate([
  79252. BABYLON.serialize()
  79253. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  79254. __decorate([
  79255. BABYLON.serialize()
  79256. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  79257. __decorate([
  79258. BABYLON.serialize()
  79259. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  79260. __decorate([
  79261. BABYLON.serialize()
  79262. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  79263. __decorate([
  79264. BABYLON.serialize()
  79265. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  79266. __decorate([
  79267. BABYLON.serialize()
  79268. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  79269. __decorate([
  79270. BABYLON.serialize()
  79271. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  79272. return StandardRenderingPipeline;
  79273. }(BABYLON.PostProcessRenderPipeline));
  79274. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  79275. })(BABYLON || (BABYLON = {}));
  79276. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  79277. var BABYLON;
  79278. (function (BABYLON) {
  79279. var FxaaPostProcess = /** @class */ (function (_super) {
  79280. __extends(FxaaPostProcess, _super);
  79281. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79282. if (camera === void 0) { camera = null; }
  79283. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79284. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  79285. var defines = _this._getDefines();
  79286. _this.updateEffect(defines);
  79287. _this.onApplyObservable.add(function (effect) {
  79288. var texelSize = _this.texelSize;
  79289. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  79290. });
  79291. return _this;
  79292. }
  79293. FxaaPostProcess.prototype._getDefines = function () {
  79294. var engine = this.getEngine();
  79295. if (!engine) {
  79296. return null;
  79297. }
  79298. var glInfo = engine.getGlInfo();
  79299. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  79300. return "#define MALI 1\n";
  79301. }
  79302. return null;
  79303. };
  79304. return FxaaPostProcess;
  79305. }(BABYLON.PostProcess));
  79306. BABYLON.FxaaPostProcess = FxaaPostProcess;
  79307. })(BABYLON || (BABYLON = {}));
  79308. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  79309. var BABYLON;
  79310. (function (BABYLON) {
  79311. /**
  79312. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  79313. */
  79314. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  79315. __extends(ChromaticAberrationPostProcess, _super);
  79316. /**
  79317. * Creates a new instance ChromaticAberrationPostProcess
  79318. * @param name The name of the effect.
  79319. * @param screenWidth The width of the screen to apply the effect on.
  79320. * @param screenHeight The height of the screen to apply the effect on.
  79321. * @param options The required width/height ratio to downsize to before computing the render pass.
  79322. * @param camera The camera to apply the render pass to.
  79323. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79324. * @param engine The engine which the post process will be applied. (default: current engine)
  79325. * @param reusable If the post process can be reused on the same frame. (default: false)
  79326. * @param textureType Type of textures used when performing the post process. (default: 0)
  79327. * @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)
  79328. */
  79329. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79331. if (blockCompilation === void 0) { blockCompilation = false; }
  79332. 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;
  79333. /**
  79334. * The amount of seperation of rgb channels (default: 30)
  79335. */
  79336. _this.aberrationAmount = 30;
  79337. /**
  79338. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  79339. */
  79340. _this.radialIntensity = 0;
  79341. /**
  79342. * 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))
  79343. */
  79344. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  79345. /**
  79346. * 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))
  79347. */
  79348. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  79349. _this.onApplyObservable.add(function (effect) {
  79350. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  79351. effect.setFloat('screen_width', screenWidth);
  79352. effect.setFloat('screen_height', screenHeight);
  79353. effect.setFloat('radialIntensity', _this.radialIntensity);
  79354. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  79355. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  79356. });
  79357. return _this;
  79358. }
  79359. return ChromaticAberrationPostProcess;
  79360. }(BABYLON.PostProcess));
  79361. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  79362. })(BABYLON || (BABYLON = {}));
  79363. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  79364. var BABYLON;
  79365. (function (BABYLON) {
  79366. /**
  79367. * The GrainPostProcess adds noise to the image at mid luminance levels
  79368. */
  79369. var GrainPostProcess = /** @class */ (function (_super) {
  79370. __extends(GrainPostProcess, _super);
  79371. /**
  79372. * Creates a new instance of @see GrainPostProcess
  79373. * @param name The name of the effect.
  79374. * @param options The required width/height ratio to downsize to before computing the render pass.
  79375. * @param camera The camera to apply the render pass to.
  79376. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79377. * @param engine The engine which the post process will be applied. (default: current engine)
  79378. * @param reusable If the post process can be reused on the same frame. (default: false)
  79379. * @param textureType Type of textures used when performing the post process. (default: 0)
  79380. * @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)
  79381. */
  79382. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79383. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79384. if (blockCompilation === void 0) { blockCompilation = false; }
  79385. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79386. /**
  79387. * The intensity of the grain added (default: 30)
  79388. */
  79389. _this.intensity = 30;
  79390. /**
  79391. * If the grain should be randomized on every frame
  79392. */
  79393. _this.animated = false;
  79394. _this.onApplyObservable.add(function (effect) {
  79395. effect.setFloat('intensity', _this.intensity);
  79396. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  79397. });
  79398. return _this;
  79399. }
  79400. return GrainPostProcess;
  79401. }(BABYLON.PostProcess));
  79402. BABYLON.GrainPostProcess = GrainPostProcess;
  79403. })(BABYLON || (BABYLON = {}));
  79404. //# sourceMappingURL=babylon.grainPostProcess.js.map
  79405. var BABYLON;
  79406. (function (BABYLON) {
  79407. /**
  79408. * The SharpenPostProcess applies a sharpen kernel to every pixel
  79409. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79410. */
  79411. var SharpenPostProcess = /** @class */ (function (_super) {
  79412. __extends(SharpenPostProcess, _super);
  79413. /**
  79414. * Creates a new instance ConvolutionPostProcess
  79415. * @param name The name of the effect.
  79416. * @param options The required width/height ratio to downsize to before computing the render pass.
  79417. * @param camera The camera to apply the render pass to.
  79418. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79419. * @param engine The engine which the post process will be applied. (default: current engine)
  79420. * @param reusable If the post process can be reused on the same frame. (default: false)
  79421. * @param textureType Type of textures used when performing the post process. (default: 0)
  79422. * @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)
  79423. */
  79424. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79425. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79426. if (blockCompilation === void 0) { blockCompilation = false; }
  79427. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79428. /**
  79429. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  79430. */
  79431. _this.colorAmount = 1.0;
  79432. /**
  79433. * How much sharpness should be applied (default: 0.3)
  79434. */
  79435. _this.edgeAmount = 0.3;
  79436. _this.onApply = function (effect) {
  79437. effect.setFloat2("screenSize", _this.width, _this.height);
  79438. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  79439. };
  79440. return _this;
  79441. }
  79442. return SharpenPostProcess;
  79443. }(BABYLON.PostProcess));
  79444. BABYLON.SharpenPostProcess = SharpenPostProcess;
  79445. })(BABYLON || (BABYLON = {}));
  79446. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  79447. var BABYLON;
  79448. (function (BABYLON) {
  79449. /**
  79450. * The Blur Post Process which blurs an image based on a kernel and direction.
  79451. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  79452. */
  79453. var BlurPostProcess = /** @class */ (function (_super) {
  79454. __extends(BlurPostProcess, _super);
  79455. /**
  79456. * Creates a new instance BlurPostProcess
  79457. * @param name The name of the effect.
  79458. * @param direction The direction in which to blur the image.
  79459. * @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.
  79460. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  79461. * @param camera The camera to apply the render pass to.
  79462. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79463. * @param engine The engine which the post process will be applied. (default: current engine)
  79464. * @param reusable If the post process can be reused on the same frame. (default: false)
  79465. * @param textureType Type of textures used when performing the post process. (default: 0)
  79466. * @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)
  79467. */
  79468. function BlurPostProcess(name,
  79469. /** The direction in which to blur the image. */
  79470. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  79471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79472. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79473. if (defines === void 0) { defines = ""; }
  79474. if (blockCompilation === void 0) { blockCompilation = false; }
  79475. 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;
  79476. _this.direction = direction;
  79477. _this.blockCompilation = blockCompilation;
  79478. _this._packedFloat = false;
  79479. _this._staticDefines = "";
  79480. _this._staticDefines = defines;
  79481. _this.onApplyObservable.add(function (effect) {
  79482. if (_this._outputTexture) {
  79483. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  79484. }
  79485. else {
  79486. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  79487. }
  79488. });
  79489. _this.kernel = kernel;
  79490. return _this;
  79491. }
  79492. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  79493. /**
  79494. * Gets the length in pixels of the blur sample region
  79495. */
  79496. get: function () {
  79497. return this._idealKernel;
  79498. },
  79499. /**
  79500. * Sets the length in pixels of the blur sample region
  79501. */
  79502. set: function (v) {
  79503. if (this._idealKernel === v) {
  79504. return;
  79505. }
  79506. v = Math.max(v, 1);
  79507. this._idealKernel = v;
  79508. this._kernel = this._nearestBestKernel(v);
  79509. if (!this.blockCompilation) {
  79510. this._updateParameters();
  79511. }
  79512. },
  79513. enumerable: true,
  79514. configurable: true
  79515. });
  79516. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  79517. /**
  79518. * Gets wether or not the blur is unpacking/repacking floats
  79519. */
  79520. get: function () {
  79521. return this._packedFloat;
  79522. },
  79523. /**
  79524. * Sets wether or not the blur needs to unpack/repack floats
  79525. */
  79526. set: function (v) {
  79527. if (this._packedFloat === v) {
  79528. return;
  79529. }
  79530. this._packedFloat = v;
  79531. if (!this.blockCompilation) {
  79532. this._updateParameters();
  79533. }
  79534. },
  79535. enumerable: true,
  79536. configurable: true
  79537. });
  79538. /**
  79539. * Updates the effect with the current post process compile time values and recompiles the shader.
  79540. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79541. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79542. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79543. * @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
  79544. * @param onCompiled Called when the shader has been compiled.
  79545. * @param onError Called if there is an error when compiling a shader.
  79546. */
  79547. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79548. if (defines === void 0) { defines = null; }
  79549. if (uniforms === void 0) { uniforms = null; }
  79550. if (samplers === void 0) { samplers = null; }
  79551. this._updateParameters(onCompiled, onError);
  79552. };
  79553. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  79554. // Generate sampling offsets and weights
  79555. var N = this._kernel;
  79556. var centerIndex = (N - 1) / 2;
  79557. // Generate Gaussian sampling weights over kernel
  79558. var offsets = [];
  79559. var weights = [];
  79560. var totalWeight = 0;
  79561. for (var i = 0; i < N; i++) {
  79562. var u = i / (N - 1);
  79563. var w = this._gaussianWeight(u * 2.0 - 1);
  79564. offsets[i] = (i - centerIndex);
  79565. weights[i] = w;
  79566. totalWeight += w;
  79567. }
  79568. // Normalize weights
  79569. for (var i = 0; i < weights.length; i++) {
  79570. weights[i] /= totalWeight;
  79571. }
  79572. // Optimize: combine samples to take advantage of hardware linear sampling
  79573. // Walk from left to center, combining pairs (symmetrically)
  79574. var linearSamplingWeights = [];
  79575. var linearSamplingOffsets = [];
  79576. var linearSamplingMap = [];
  79577. for (var i = 0; i <= centerIndex; i += 2) {
  79578. var j = Math.min(i + 1, Math.floor(centerIndex));
  79579. var singleCenterSample = i === j;
  79580. if (singleCenterSample) {
  79581. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79582. }
  79583. else {
  79584. var sharedCell = j === centerIndex;
  79585. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  79586. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  79587. if (offsetLinear === 0) {
  79588. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79589. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  79590. }
  79591. else {
  79592. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  79593. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  79594. }
  79595. }
  79596. }
  79597. for (var i = 0; i < linearSamplingMap.length; i++) {
  79598. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  79599. linearSamplingWeights[i] = linearSamplingMap[i].w;
  79600. }
  79601. // Replace with optimized
  79602. offsets = linearSamplingOffsets;
  79603. weights = linearSamplingWeights;
  79604. // Generate shaders
  79605. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  79606. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  79607. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  79608. var defines = "";
  79609. defines += this._staticDefines;
  79610. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  79611. if (this._staticDefines.indexOf("DOF") != -1) {
  79612. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  79613. varyingCount--;
  79614. }
  79615. for (var i = 0; i < varyingCount; i++) {
  79616. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  79617. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  79618. }
  79619. var depCount = 0;
  79620. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  79621. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  79622. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  79623. depCount++;
  79624. }
  79625. if (this.packedFloat) {
  79626. defines += "#define PACKEDFLOAT 1";
  79627. }
  79628. this.blockCompilation = false;
  79629. _super.prototype.updateEffect.call(this, defines, null, null, {
  79630. varyingCount: varyingCount,
  79631. depCount: depCount
  79632. }, onCompiled, onError);
  79633. };
  79634. /**
  79635. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  79636. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  79637. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  79638. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  79639. * The gaps between physical kernels are compensated for in the weighting of the samples
  79640. * @param idealKernel Ideal blur kernel.
  79641. * @return Nearest best kernel.
  79642. */
  79643. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  79644. var v = Math.round(idealKernel);
  79645. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  79646. var k = _a[_i];
  79647. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  79648. return Math.max(k, 3);
  79649. }
  79650. }
  79651. return Math.max(v, 3);
  79652. };
  79653. /**
  79654. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  79655. * @param x The point on the Gaussian distribution to sample.
  79656. * @return the value of the Gaussian function at x.
  79657. */
  79658. BlurPostProcess.prototype._gaussianWeight = function (x) {
  79659. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  79660. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  79661. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  79662. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  79663. // truncated at around 1.3% of peak strength.
  79664. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  79665. var sigma = (1 / 3);
  79666. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  79667. var exponent = -((x * x) / (2.0 * sigma * sigma));
  79668. var weight = (1.0 / denominator) * Math.exp(exponent);
  79669. return weight;
  79670. };
  79671. /**
  79672. * Generates a string that can be used as a floating point number in GLSL.
  79673. * @param x Value to print.
  79674. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  79675. * @return GLSL float string.
  79676. */
  79677. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  79678. if (decimalFigures === void 0) { decimalFigures = 8; }
  79679. return x.toFixed(decimalFigures).replace(/0+$/, '');
  79680. };
  79681. return BlurPostProcess;
  79682. }(BABYLON.PostProcess));
  79683. BABYLON.BlurPostProcess = BlurPostProcess;
  79684. })(BABYLON || (BABYLON = {}));
  79685. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79686. var BABYLON;
  79687. (function (BABYLON) {
  79688. /**
  79689. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79690. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79691. * based on samples that have a large difference in distance than the center pixel.
  79692. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79693. */
  79694. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79695. __extends(DepthOfFieldBlurPostProcess, _super);
  79696. /**
  79697. * Creates a new instance CircleOfConfusionPostProcess
  79698. * @param name The name of the effect.
  79699. * @param scene The scene the effect belongs to.
  79700. * @param direction The direction the blur should be applied.
  79701. * @param kernel The size of the kernel used to blur.
  79702. * @param options The required width/height ratio to downsize to before computing the render pass.
  79703. * @param camera The camera to apply the render pass to.
  79704. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79705. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79706. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79707. * @param engine The engine which the post process will be applied. (default: current engine)
  79708. * @param reusable If the post process can be reused on the same frame. (default: false)
  79709. * @param textureType Type of textures used when performing the post process. (default: 0)
  79710. * @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)
  79711. */
  79712. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79713. if (imageToBlur === void 0) { imageToBlur = null; }
  79714. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79715. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79716. if (blockCompilation === void 0) { blockCompilation = false; }
  79717. 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;
  79718. _this.direction = direction;
  79719. _this.onApplyObservable.add(function (effect) {
  79720. if (imageToBlur != null) {
  79721. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79722. }
  79723. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79724. if (scene.activeCamera) {
  79725. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79726. }
  79727. });
  79728. return _this;
  79729. }
  79730. return DepthOfFieldBlurPostProcess;
  79731. }(BABYLON.BlurPostProcess));
  79732. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79733. })(BABYLON || (BABYLON = {}));
  79734. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79735. var BABYLON;
  79736. (function (BABYLON) {
  79737. /**
  79738. * Options to be set when merging outputs from the default pipeline.
  79739. */
  79740. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79741. function DepthOfFieldMergePostProcessOptions() {
  79742. }
  79743. return DepthOfFieldMergePostProcessOptions;
  79744. }());
  79745. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79746. /**
  79747. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79748. */
  79749. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79750. __extends(DepthOfFieldMergePostProcess, _super);
  79751. /**
  79752. * Creates a new instance of DepthOfFieldMergePostProcess
  79753. * @param name The name of the effect.
  79754. * @param originalFromInput Post process which's input will be used for the merge.
  79755. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79756. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79757. * @param options The required width/height ratio to downsize to before computing the render pass.
  79758. * @param camera The camera to apply the render pass to.
  79759. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79760. * @param engine The engine which the post process will be applied. (default: current engine)
  79761. * @param reusable If the post process can be reused on the same frame. (default: false)
  79762. * @param textureType Type of textures used when performing the post process. (default: 0)
  79763. * @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)
  79764. */
  79765. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79766. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79767. if (blockCompilation === void 0) { blockCompilation = false; }
  79768. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79769. _this.blurSteps = blurSteps;
  79770. _this.onApplyObservable.add(function (effect) {
  79771. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79772. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79773. blurSteps.forEach(function (step, index) {
  79774. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79775. });
  79776. });
  79777. if (!blockCompilation) {
  79778. _this.updateEffect();
  79779. }
  79780. return _this;
  79781. }
  79782. /**
  79783. * Updates the effect with the current post process compile time values and recompiles the shader.
  79784. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79785. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79786. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79787. * @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
  79788. * @param onCompiled Called when the shader has been compiled.
  79789. * @param onError Called if there is an error when compiling a shader.
  79790. */
  79791. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79792. if (defines === void 0) { defines = null; }
  79793. if (uniforms === void 0) { uniforms = null; }
  79794. if (samplers === void 0) { samplers = null; }
  79795. if (!defines) {
  79796. defines = "";
  79797. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  79798. }
  79799. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  79800. };
  79801. return DepthOfFieldMergePostProcess;
  79802. }(BABYLON.PostProcess));
  79803. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  79804. })(BABYLON || (BABYLON = {}));
  79805. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  79806. var BABYLON;
  79807. (function (BABYLON) {
  79808. /**
  79809. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  79810. */
  79811. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  79812. __extends(CircleOfConfusionPostProcess, _super);
  79813. /**
  79814. * Creates a new instance CircleOfConfusionPostProcess
  79815. * @param name The name of the effect.
  79816. * @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.
  79817. * @param options The required width/height ratio to downsize to before computing the render pass.
  79818. * @param camera The camera to apply the render pass to.
  79819. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79820. * @param engine The engine which the post process will be applied. (default: current engine)
  79821. * @param reusable If the post process can be reused on the same frame. (default: false)
  79822. * @param textureType Type of textures used when performing the post process. (default: 0)
  79823. * @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)
  79824. */
  79825. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79826. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79827. if (blockCompilation === void 0) { blockCompilation = false; }
  79828. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79829. /**
  79830. * 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.
  79831. */
  79832. _this.lensSize = 50;
  79833. /**
  79834. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79835. */
  79836. _this.fStop = 1.4;
  79837. /**
  79838. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79839. */
  79840. _this.focusDistance = 2000;
  79841. /**
  79842. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  79843. */
  79844. _this.focalLength = 50;
  79845. _this._depthTexture = null;
  79846. _this._depthTexture = depthTexture;
  79847. _this.onApplyObservable.add(function (effect) {
  79848. if (!_this._depthTexture) {
  79849. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  79850. return;
  79851. }
  79852. effect.setTexture("depthSampler", _this._depthTexture);
  79853. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  79854. var aperture = _this.lensSize / _this.fStop;
  79855. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  79856. effect.setFloat('focusDistance', _this.focusDistance);
  79857. effect.setFloat('cocPrecalculation', cocPrecalculation);
  79858. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  79859. });
  79860. return _this;
  79861. }
  79862. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  79863. /**
  79864. * 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.
  79865. */
  79866. set: function (value) {
  79867. this._depthTexture = value;
  79868. },
  79869. enumerable: true,
  79870. configurable: true
  79871. });
  79872. return CircleOfConfusionPostProcess;
  79873. }(BABYLON.PostProcess));
  79874. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  79875. })(BABYLON || (BABYLON = {}));
  79876. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  79877. var BABYLON;
  79878. (function (BABYLON) {
  79879. /**
  79880. * Specifies the level of max blur that should be applied when using the depth of field effect
  79881. */
  79882. var DepthOfFieldEffectBlurLevel;
  79883. (function (DepthOfFieldEffectBlurLevel) {
  79884. /**
  79885. * Subtle blur
  79886. */
  79887. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  79888. /**
  79889. * Medium blur
  79890. */
  79891. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  79892. /**
  79893. * Large blur
  79894. */
  79895. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  79896. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  79897. ;
  79898. /**
  79899. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  79900. */
  79901. var DepthOfFieldEffect = /** @class */ (function (_super) {
  79902. __extends(DepthOfFieldEffect, _super);
  79903. /**
  79904. * Creates a new instance DepthOfFieldEffect
  79905. * @param scene The scene the effect belongs to.
  79906. * @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.
  79907. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79908. * @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)
  79909. */
  79910. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  79911. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  79912. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79913. if (blockCompilation === void 0) { blockCompilation = false; }
  79914. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79915. return _this._effects;
  79916. }, true) || this;
  79917. /**
  79918. * @hidden Internal post processes in depth of field effect
  79919. */
  79920. _this._effects = [];
  79921. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79922. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79923. // 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)
  79924. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79925. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79926. _this._depthOfFieldBlurY = [];
  79927. _this._depthOfFieldBlurX = [];
  79928. var blurCount = 1;
  79929. var kernelSize = 15;
  79930. switch (blurLevel) {
  79931. case DepthOfFieldEffectBlurLevel.High: {
  79932. blurCount = 3;
  79933. kernelSize = 51;
  79934. break;
  79935. }
  79936. case DepthOfFieldEffectBlurLevel.Medium: {
  79937. blurCount = 2;
  79938. kernelSize = 31;
  79939. break;
  79940. }
  79941. default: {
  79942. kernelSize = 15;
  79943. blurCount = 1;
  79944. break;
  79945. }
  79946. }
  79947. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79948. var ratio = 1.0;
  79949. for (var i = 0; i < blurCount; i++) {
  79950. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79951. blurY.autoClear = false;
  79952. ratio = 0.75 / Math.pow(2, i);
  79953. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79954. blurX.autoClear = false;
  79955. _this._depthOfFieldBlurY.push(blurY);
  79956. _this._depthOfFieldBlurX.push(blurX);
  79957. }
  79958. // Set all post processes on the effect.
  79959. _this._effects = [_this._circleOfConfusion];
  79960. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79961. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79962. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79963. }
  79964. // Merge blurred images with original image based on circleOfConfusion
  79965. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79966. _this._dofMerge.autoClear = false;
  79967. _this._effects.push(_this._dofMerge);
  79968. return _this;
  79969. }
  79970. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79971. get: function () {
  79972. return this._circleOfConfusion.focalLength;
  79973. },
  79974. /**
  79975. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79976. */
  79977. set: function (value) {
  79978. this._circleOfConfusion.focalLength = value;
  79979. },
  79980. enumerable: true,
  79981. configurable: true
  79982. });
  79983. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79984. get: function () {
  79985. return this._circleOfConfusion.fStop;
  79986. },
  79987. /**
  79988. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79989. */
  79990. set: function (value) {
  79991. this._circleOfConfusion.fStop = value;
  79992. },
  79993. enumerable: true,
  79994. configurable: true
  79995. });
  79996. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79997. get: function () {
  79998. return this._circleOfConfusion.focusDistance;
  79999. },
  80000. /**
  80001. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80002. */
  80003. set: function (value) {
  80004. this._circleOfConfusion.focusDistance = value;
  80005. },
  80006. enumerable: true,
  80007. configurable: true
  80008. });
  80009. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  80010. get: function () {
  80011. return this._circleOfConfusion.lensSize;
  80012. },
  80013. /**
  80014. * 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.
  80015. */
  80016. set: function (value) {
  80017. this._circleOfConfusion.lensSize = value;
  80018. },
  80019. enumerable: true,
  80020. configurable: true
  80021. });
  80022. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  80023. /**
  80024. * 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.
  80025. */
  80026. set: function (value) {
  80027. this._circleOfConfusion.depthTexture = value;
  80028. },
  80029. enumerable: true,
  80030. configurable: true
  80031. });
  80032. /**
  80033. * Disposes each of the internal effects for a given camera.
  80034. * @param camera The camera to dispose the effect on.
  80035. */
  80036. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  80037. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80038. this._effects[effectIndex].dispose(camera);
  80039. }
  80040. };
  80041. /**
  80042. * @hidden Internal
  80043. */
  80044. DepthOfFieldEffect.prototype._updateEffects = function () {
  80045. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80046. this._effects[effectIndex].updateEffect();
  80047. }
  80048. };
  80049. /**
  80050. * Internal
  80051. * @returns if all the contained post processes are ready.
  80052. * @hidden
  80053. */
  80054. DepthOfFieldEffect.prototype._isReady = function () {
  80055. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80056. if (!this._effects[effectIndex].isReady()) {
  80057. return false;
  80058. }
  80059. }
  80060. return true;
  80061. };
  80062. return DepthOfFieldEffect;
  80063. }(BABYLON.PostProcessRenderEffect));
  80064. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  80065. })(BABYLON || (BABYLON = {}));
  80066. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  80067. var BABYLON;
  80068. (function (BABYLON) {
  80069. /**
  80070. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80071. */
  80072. var BloomMergePostProcess = /** @class */ (function (_super) {
  80073. __extends(BloomMergePostProcess, _super);
  80074. /**
  80075. * Creates a new instance of @see BloomMergePostProcess
  80076. * @param name The name of the effect.
  80077. * @param originalFromInput Post process which's input will be used for the merge.
  80078. * @param blurred Blurred highlights post process which's output will be used.
  80079. * @param weight Weight of the bloom to be added to the original input.
  80080. * @param options The required width/height ratio to downsize to before computing the render pass.
  80081. * @param camera The camera to apply the render pass to.
  80082. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80083. * @param engine The engine which the post process will be applied. (default: current engine)
  80084. * @param reusable If the post process can be reused on the same frame. (default: false)
  80085. * @param textureType Type of textures used when performing the post process. (default: 0)
  80086. * @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)
  80087. */
  80088. function BloomMergePostProcess(name, originalFromInput, blurred,
  80089. /** Weight of the bloom to be added to the original input. */
  80090. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80092. if (blockCompilation === void 0) { blockCompilation = false; }
  80093. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80094. _this.weight = weight;
  80095. _this.onApplyObservable.add(function (effect) {
  80096. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80097. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  80098. effect.setFloat("bloomWeight", _this.weight);
  80099. });
  80100. if (!blockCompilation) {
  80101. _this.updateEffect();
  80102. }
  80103. return _this;
  80104. }
  80105. return BloomMergePostProcess;
  80106. }(BABYLON.PostProcess));
  80107. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  80108. })(BABYLON || (BABYLON = {}));
  80109. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  80110. var BABYLON;
  80111. (function (BABYLON) {
  80112. /**
  80113. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  80114. */
  80115. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  80116. __extends(ExtractHighlightsPostProcess, _super);
  80117. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80118. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80119. if (blockCompilation === void 0) { blockCompilation = false; }
  80120. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80121. /**
  80122. * The luminance threshold, pixels below this value will be set to black.
  80123. */
  80124. _this.threshold = 0.9;
  80125. /** @hidden */
  80126. _this._exposure = 1;
  80127. /**
  80128. * Post process which has the input texture to be used when performing highlight extraction
  80129. * @hidden
  80130. */
  80131. _this._inputPostProcess = null;
  80132. _this.onApplyObservable.add(function (effect) {
  80133. if (_this._inputPostProcess) {
  80134. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  80135. }
  80136. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  80137. effect.setFloat('exposure', _this._exposure);
  80138. });
  80139. return _this;
  80140. }
  80141. return ExtractHighlightsPostProcess;
  80142. }(BABYLON.PostProcess));
  80143. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  80144. })(BABYLON || (BABYLON = {}));
  80145. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  80146. var BABYLON;
  80147. (function (BABYLON) {
  80148. /**
  80149. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  80150. */
  80151. var BloomEffect = /** @class */ (function (_super) {
  80152. __extends(BloomEffect, _super);
  80153. /**
  80154. * Creates a new instance of @see BloomEffect
  80155. * @param scene The scene the effect belongs to.
  80156. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  80157. * @param bloomKernel The size of the kernel to be used when applying the blur.
  80158. * @param bloomWeight The the strength of bloom.
  80159. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80160. * @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)
  80161. */
  80162. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  80163. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80164. if (blockCompilation === void 0) { blockCompilation = false; }
  80165. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  80166. return _this._effects;
  80167. }, true) || this;
  80168. _this.bloomScale = bloomScale;
  80169. /**
  80170. * @hidden Internal
  80171. */
  80172. _this._effects = [];
  80173. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80174. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  80175. _this._blurX.alwaysForcePOT = true;
  80176. _this._blurX.autoClear = false;
  80177. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  80178. _this._blurY.alwaysForcePOT = true;
  80179. _this._blurY.autoClear = false;
  80180. _this.kernel = bloomKernel;
  80181. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  80182. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80183. _this._merge.autoClear = false;
  80184. _this._effects.push(_this._merge);
  80185. return _this;
  80186. }
  80187. Object.defineProperty(BloomEffect.prototype, "threshold", {
  80188. /**
  80189. * The luminance threshold to find bright areas of the image to bloom.
  80190. */
  80191. get: function () {
  80192. return this._downscale.threshold;
  80193. },
  80194. set: function (value) {
  80195. this._downscale.threshold = value;
  80196. },
  80197. enumerable: true,
  80198. configurable: true
  80199. });
  80200. Object.defineProperty(BloomEffect.prototype, "weight", {
  80201. /**
  80202. * The strength of the bloom.
  80203. */
  80204. get: function () {
  80205. return this._merge.weight;
  80206. },
  80207. set: function (value) {
  80208. this._merge.weight = value;
  80209. },
  80210. enumerable: true,
  80211. configurable: true
  80212. });
  80213. Object.defineProperty(BloomEffect.prototype, "kernel", {
  80214. /**
  80215. * Specifies the size of the bloom blur kernel, relative to the final output size
  80216. */
  80217. get: function () {
  80218. return this._blurX.kernel / this.bloomScale;
  80219. },
  80220. set: function (value) {
  80221. this._blurX.kernel = value * this.bloomScale;
  80222. this._blurY.kernel = value * this.bloomScale;
  80223. },
  80224. enumerable: true,
  80225. configurable: true
  80226. });
  80227. /**
  80228. * Disposes each of the internal effects for a given camera.
  80229. * @param camera The camera to dispose the effect on.
  80230. */
  80231. BloomEffect.prototype.disposeEffects = function (camera) {
  80232. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80233. this._effects[effectIndex].dispose(camera);
  80234. }
  80235. };
  80236. /**
  80237. * @hidden Internal
  80238. */
  80239. BloomEffect.prototype._updateEffects = function () {
  80240. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80241. this._effects[effectIndex].updateEffect();
  80242. }
  80243. };
  80244. /**
  80245. * Internal
  80246. * @returns if all the contained post processes are ready.
  80247. * @hidden
  80248. */
  80249. BloomEffect.prototype._isReady = function () {
  80250. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80251. if (!this._effects[effectIndex].isReady()) {
  80252. return false;
  80253. }
  80254. }
  80255. return true;
  80256. };
  80257. return BloomEffect;
  80258. }(BABYLON.PostProcessRenderEffect));
  80259. BABYLON.BloomEffect = BloomEffect;
  80260. })(BABYLON || (BABYLON = {}));
  80261. //# sourceMappingURL=babylon.bloomEffect.js.map
  80262. var BABYLON;
  80263. (function (BABYLON) {
  80264. /**
  80265. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  80266. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  80267. */
  80268. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  80269. __extends(DefaultRenderingPipeline, _super);
  80270. /**
  80271. * @constructor
  80272. * @param {string} name - The rendering pipeline name (default: "")
  80273. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  80274. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  80275. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  80276. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  80277. */
  80278. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  80279. if (name === void 0) { name = ""; }
  80280. if (hdr === void 0) { hdr = true; }
  80281. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  80282. if (automaticBuild === void 0) { automaticBuild = true; }
  80283. var _this = _super.call(this, scene.getEngine(), name) || this;
  80284. _this._camerasToBeAttached = [];
  80285. /**
  80286. * ID of the sharpen post process,
  80287. */
  80288. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  80289. /**
  80290. * ID of the image processing post process;
  80291. */
  80292. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  80293. /**
  80294. * ID of the Fast Approximate Anti-Aliasing post process;
  80295. */
  80296. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  80297. /**
  80298. * ID of the chromatic aberration post process,
  80299. */
  80300. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  80301. /**
  80302. * ID of the grain post process
  80303. */
  80304. _this.GrainPostProcessId = "GrainPostProcessEffect";
  80305. /**
  80306. * Glow post process which adds a glow to emmisive areas of the image
  80307. */
  80308. _this._glowLayer = null;
  80309. /**
  80310. * Animations which can be used to tweak settings over a period of time
  80311. */
  80312. _this.animations = [];
  80313. _this._imageProcessingConfigurationObserver = null;
  80314. // Values
  80315. _this._sharpenEnabled = false;
  80316. _this._bloomEnabled = false;
  80317. _this._depthOfFieldEnabled = false;
  80318. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  80319. _this._fxaaEnabled = false;
  80320. _this._imageProcessingEnabled = true;
  80321. _this._bloomScale = 0.5;
  80322. _this._chromaticAberrationEnabled = false;
  80323. _this._grainEnabled = false;
  80324. _this._buildAllowed = true;
  80325. _this._resizeObserver = null;
  80326. _this._hardwareScaleLevel = 1.0;
  80327. _this._bloomKernel = 64;
  80328. /**
  80329. * Specifies the weight of the bloom in the final rendering
  80330. */
  80331. _this._bloomWeight = 0.15;
  80332. /**
  80333. * Specifies the luma threshold for the area that will be blurred by the bloom
  80334. */
  80335. _this._bloomThreshold = 0.9;
  80336. _this._samples = 1;
  80337. _this._hasCleared = false;
  80338. _this._prevPostProcess = null;
  80339. _this._prevPrevPostProcess = null;
  80340. _this._cameras = cameras || scene.cameras;
  80341. _this._cameras = _this._cameras.slice();
  80342. _this._camerasToBeAttached = _this._cameras.slice();
  80343. _this._buildAllowed = automaticBuild;
  80344. // Initialize
  80345. _this._scene = scene;
  80346. var caps = _this._scene.getEngine().getCaps();
  80347. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  80348. // Misc
  80349. if (_this._hdr) {
  80350. if (caps.textureHalfFloatRender) {
  80351. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80352. }
  80353. else if (caps.textureFloatRender) {
  80354. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80355. }
  80356. }
  80357. else {
  80358. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80359. }
  80360. // Attach
  80361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80362. var engine = _this._scene.getEngine();
  80363. // Create post processes before hand so they can be modified before enabled.
  80364. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  80365. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  80366. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  80367. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  80368. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  80369. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  80370. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  80371. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  80372. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  80373. _this._resizeObserver = engine.onResizeObservable.add(function () {
  80374. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  80375. _this.bloomKernel = _this.bloomKernel;
  80376. });
  80377. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  80378. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  80379. });
  80380. _this._buildPipeline();
  80381. return _this;
  80382. }
  80383. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  80384. get: function () {
  80385. return this._sharpenEnabled;
  80386. },
  80387. /**
  80388. * Enable or disable the sharpen process from the pipeline
  80389. */
  80390. set: function (enabled) {
  80391. if (this._sharpenEnabled === enabled) {
  80392. return;
  80393. }
  80394. this._sharpenEnabled = enabled;
  80395. this._buildPipeline();
  80396. },
  80397. enumerable: true,
  80398. configurable: true
  80399. });
  80400. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  80401. /**
  80402. * Specifies the size of the bloom blur kernel, relative to the final output size
  80403. */
  80404. get: function () {
  80405. return this._bloomKernel;
  80406. },
  80407. set: function (value) {
  80408. this._bloomKernel = value;
  80409. this.bloom.kernel = value / this._hardwareScaleLevel;
  80410. },
  80411. enumerable: true,
  80412. configurable: true
  80413. });
  80414. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  80415. get: function () {
  80416. return this._bloomWeight;
  80417. },
  80418. /**
  80419. * The strength of the bloom.
  80420. */
  80421. set: function (value) {
  80422. if (this._bloomWeight === value) {
  80423. return;
  80424. }
  80425. this.bloom.weight = value;
  80426. this._bloomWeight = value;
  80427. },
  80428. enumerable: true,
  80429. configurable: true
  80430. });
  80431. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  80432. get: function () {
  80433. return this._bloomThreshold;
  80434. },
  80435. /**
  80436. * The strength of the bloom.
  80437. */
  80438. set: function (value) {
  80439. if (this._bloomThreshold === value) {
  80440. return;
  80441. }
  80442. this.bloom.threshold = value;
  80443. this._bloomThreshold = value;
  80444. },
  80445. enumerable: true,
  80446. configurable: true
  80447. });
  80448. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  80449. get: function () {
  80450. return this._bloomScale;
  80451. },
  80452. /**
  80453. * The scale of the bloom, lower value will provide better performance.
  80454. */
  80455. set: function (value) {
  80456. if (this._bloomScale === value) {
  80457. return;
  80458. }
  80459. this._bloomScale = value;
  80460. // recreate bloom and dispose old as this setting is not dynamic
  80461. this._rebuildBloom();
  80462. this._buildPipeline();
  80463. },
  80464. enumerable: true,
  80465. configurable: true
  80466. });
  80467. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  80468. get: function () {
  80469. return this._bloomEnabled;
  80470. },
  80471. /**
  80472. * Enable or disable the bloom from the pipeline
  80473. */
  80474. set: function (enabled) {
  80475. if (this._bloomEnabled === enabled) {
  80476. return;
  80477. }
  80478. this._bloomEnabled = enabled;
  80479. this._buildPipeline();
  80480. },
  80481. enumerable: true,
  80482. configurable: true
  80483. });
  80484. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  80485. // recreate bloom and dispose old as this setting is not dynamic
  80486. var oldBloom = this.bloom;
  80487. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  80488. this.bloom.threshold = oldBloom.threshold;
  80489. for (var i = 0; i < this._cameras.length; i++) {
  80490. oldBloom.disposeEffects(this._cameras[i]);
  80491. }
  80492. };
  80493. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  80494. /**
  80495. * If the depth of field is enabled.
  80496. */
  80497. get: function () {
  80498. return this._depthOfFieldEnabled;
  80499. },
  80500. set: function (enabled) {
  80501. if (this._depthOfFieldEnabled === enabled) {
  80502. return;
  80503. }
  80504. this._depthOfFieldEnabled = enabled;
  80505. this._buildPipeline();
  80506. },
  80507. enumerable: true,
  80508. configurable: true
  80509. });
  80510. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  80511. /**
  80512. * Blur level of the depth of field effect. (Higher blur will effect performance)
  80513. */
  80514. get: function () {
  80515. return this._depthOfFieldBlurLevel;
  80516. },
  80517. set: function (value) {
  80518. if (this._depthOfFieldBlurLevel === value) {
  80519. return;
  80520. }
  80521. this._depthOfFieldBlurLevel = value;
  80522. // recreate dof and dispose old as this setting is not dynamic
  80523. var oldDof = this.depthOfField;
  80524. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  80525. this.depthOfField.focalLength = oldDof.focalLength;
  80526. this.depthOfField.focusDistance = oldDof.focusDistance;
  80527. this.depthOfField.fStop = oldDof.fStop;
  80528. this.depthOfField.lensSize = oldDof.lensSize;
  80529. for (var i = 0; i < this._cameras.length; i++) {
  80530. oldDof.disposeEffects(this._cameras[i]);
  80531. }
  80532. this._buildPipeline();
  80533. },
  80534. enumerable: true,
  80535. configurable: true
  80536. });
  80537. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  80538. get: function () {
  80539. return this._fxaaEnabled;
  80540. },
  80541. /**
  80542. * If the anti aliasing is enabled.
  80543. */
  80544. set: function (enabled) {
  80545. if (this._fxaaEnabled === enabled) {
  80546. return;
  80547. }
  80548. this._fxaaEnabled = enabled;
  80549. this._buildPipeline();
  80550. },
  80551. enumerable: true,
  80552. configurable: true
  80553. });
  80554. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  80555. get: function () {
  80556. return this._samples;
  80557. },
  80558. /**
  80559. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  80560. */
  80561. set: function (sampleCount) {
  80562. if (this._samples === sampleCount) {
  80563. return;
  80564. }
  80565. this._samples = sampleCount;
  80566. this._buildPipeline();
  80567. },
  80568. enumerable: true,
  80569. configurable: true
  80570. });
  80571. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  80572. get: function () {
  80573. return this._imageProcessingEnabled;
  80574. },
  80575. /**
  80576. * If image processing is enabled.
  80577. */
  80578. set: function (enabled) {
  80579. if (this._imageProcessingEnabled === enabled) {
  80580. return;
  80581. }
  80582. this._imageProcessingEnabled = enabled;
  80583. this._buildPipeline();
  80584. },
  80585. enumerable: true,
  80586. configurable: true
  80587. });
  80588. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  80589. get: function () {
  80590. return this._glowLayer == null;
  80591. },
  80592. /**
  80593. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  80594. */
  80595. set: function (enabled) {
  80596. if (enabled && !this._glowLayer) {
  80597. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  80598. }
  80599. else if (!enabled && this._glowLayer) {
  80600. this._glowLayer.dispose();
  80601. this._glowLayer = null;
  80602. }
  80603. },
  80604. enumerable: true,
  80605. configurable: true
  80606. });
  80607. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  80608. get: function () {
  80609. return this._chromaticAberrationEnabled;
  80610. },
  80611. /**
  80612. * Enable or disable the chromaticAberration process from the pipeline
  80613. */
  80614. set: function (enabled) {
  80615. if (this._chromaticAberrationEnabled === enabled) {
  80616. return;
  80617. }
  80618. this._chromaticAberrationEnabled = enabled;
  80619. this._buildPipeline();
  80620. },
  80621. enumerable: true,
  80622. configurable: true
  80623. });
  80624. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  80625. get: function () {
  80626. return this._grainEnabled;
  80627. },
  80628. /**
  80629. * Enable or disable the grain process from the pipeline
  80630. */
  80631. set: function (enabled) {
  80632. if (this._grainEnabled === enabled) {
  80633. return;
  80634. }
  80635. this._grainEnabled = enabled;
  80636. this._buildPipeline();
  80637. },
  80638. enumerable: true,
  80639. configurable: true
  80640. });
  80641. /**
  80642. * Force the compilation of the entire pipeline.
  80643. */
  80644. DefaultRenderingPipeline.prototype.prepare = function () {
  80645. var previousState = this._buildAllowed;
  80646. this._buildAllowed = true;
  80647. this._buildPipeline();
  80648. this._buildAllowed = previousState;
  80649. };
  80650. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  80651. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  80652. if (this._hasCleared) {
  80653. postProcess.autoClear = false;
  80654. }
  80655. else {
  80656. postProcess.autoClear = true;
  80657. this._scene.autoClear = false;
  80658. this._hasCleared = true;
  80659. }
  80660. if (!skipTextureSharing) {
  80661. if (this._prevPrevPostProcess) {
  80662. postProcess.shareOutputWith(this._prevPrevPostProcess);
  80663. }
  80664. else {
  80665. postProcess.useOwnOutput();
  80666. }
  80667. if (this._prevPostProcess) {
  80668. this._prevPrevPostProcess = this._prevPostProcess;
  80669. }
  80670. this._prevPostProcess = postProcess;
  80671. }
  80672. };
  80673. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  80674. var _this = this;
  80675. if (!this._buildAllowed) {
  80676. return;
  80677. }
  80678. this._scene.autoClear = true;
  80679. var engine = this._scene.getEngine();
  80680. this._disposePostProcesses();
  80681. if (this._cameras !== null) {
  80682. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80683. // get back cameras to be used to reattach pipeline
  80684. this._cameras = this._camerasToBeAttached.slice();
  80685. }
  80686. this._reset();
  80687. this._prevPostProcess = null;
  80688. this._prevPrevPostProcess = null;
  80689. this._hasCleared = false;
  80690. if (this.depthOfFieldEnabled) {
  80691. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80692. this.depthOfField.depthTexture = depthTexture;
  80693. if (!this.depthOfField._isReady()) {
  80694. this.depthOfField._updateEffects();
  80695. }
  80696. this.addEffect(this.depthOfField);
  80697. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80698. }
  80699. if (this.bloomEnabled) {
  80700. if (!this.bloom._isReady()) {
  80701. this.bloom._updateEffects();
  80702. }
  80703. this.addEffect(this.bloom);
  80704. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80705. }
  80706. if (this._imageProcessingEnabled) {
  80707. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80708. if (this._hdr) {
  80709. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80710. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80711. }
  80712. else {
  80713. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80714. }
  80715. }
  80716. if (this.sharpenEnabled) {
  80717. if (!this.sharpen.isReady()) {
  80718. this.sharpen.updateEffect();
  80719. }
  80720. this.addEffect(this._sharpenEffect);
  80721. this._setAutoClearAndTextureSharing(this.sharpen);
  80722. }
  80723. if (this.grainEnabled) {
  80724. if (!this.grain.isReady()) {
  80725. this.grain.updateEffect();
  80726. }
  80727. this.addEffect(this._grainEffect);
  80728. this._setAutoClearAndTextureSharing(this.grain);
  80729. }
  80730. if (this.chromaticAberrationEnabled) {
  80731. if (!this.chromaticAberration.isReady()) {
  80732. this.chromaticAberration.updateEffect();
  80733. }
  80734. this.addEffect(this._chromaticAberrationEffect);
  80735. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80736. }
  80737. if (this.fxaaEnabled) {
  80738. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80739. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80740. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80741. }
  80742. if (this._cameras !== null) {
  80743. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80744. }
  80745. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80746. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80747. }
  80748. };
  80749. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80750. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80751. for (var i = 0; i < this._cameras.length; i++) {
  80752. var camera = this._cameras[i];
  80753. if (this.imageProcessing) {
  80754. this.imageProcessing.dispose(camera);
  80755. }
  80756. if (this.fxaa) {
  80757. this.fxaa.dispose(camera);
  80758. }
  80759. // These are created in the constructor and should not be disposed on every pipeline change
  80760. if (disposeNonRecreated) {
  80761. if (this.sharpen) {
  80762. this.sharpen.dispose(camera);
  80763. }
  80764. if (this.depthOfField) {
  80765. this.depthOfField.disposeEffects(camera);
  80766. }
  80767. if (this.bloom) {
  80768. this.bloom.disposeEffects(camera);
  80769. }
  80770. if (this.chromaticAberration) {
  80771. this.chromaticAberration.dispose(camera);
  80772. }
  80773. if (this.grain) {
  80774. this.grain.dispose(camera);
  80775. }
  80776. if (this._glowLayer) {
  80777. this._glowLayer.dispose();
  80778. }
  80779. }
  80780. }
  80781. this.imageProcessing = null;
  80782. this.fxaa = null;
  80783. if (disposeNonRecreated) {
  80784. this.sharpen = null;
  80785. this._sharpenEffect = null;
  80786. this.depthOfField = null;
  80787. this.bloom = null;
  80788. this.chromaticAberration = null;
  80789. this._chromaticAberrationEffect = null;
  80790. this.grain = null;
  80791. this._grainEffect = null;
  80792. this._glowLayer = null;
  80793. }
  80794. };
  80795. /**
  80796. * Adds a camera to the pipeline
  80797. * @param camera the camera to be added
  80798. */
  80799. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  80800. this._camerasToBeAttached.push(camera);
  80801. this._buildPipeline();
  80802. };
  80803. /**
  80804. * Removes a camera from the pipeline
  80805. * @param camera the camera to remove
  80806. */
  80807. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  80808. var index = this._camerasToBeAttached.indexOf(camera);
  80809. this._camerasToBeAttached.splice(index, 1);
  80810. this._buildPipeline();
  80811. };
  80812. /**
  80813. * Dispose of the pipeline and stop all post processes
  80814. */
  80815. DefaultRenderingPipeline.prototype.dispose = function () {
  80816. this._disposePostProcesses(true);
  80817. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80818. this._scene.autoClear = true;
  80819. if (this._resizeObserver) {
  80820. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  80821. this._resizeObserver = null;
  80822. }
  80823. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  80824. _super.prototype.dispose.call(this);
  80825. };
  80826. /**
  80827. * Serialize the rendering pipeline (Used when exporting)
  80828. * @returns the serialized object
  80829. */
  80830. DefaultRenderingPipeline.prototype.serialize = function () {
  80831. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80832. serializationObject.customType = "DefaultRenderingPipeline";
  80833. return serializationObject;
  80834. };
  80835. /**
  80836. * Parse the serialized pipeline
  80837. * @param source Source pipeline.
  80838. * @param scene The scene to load the pipeline to.
  80839. * @param rootUrl The URL of the serialized pipeline.
  80840. * @returns An instantiated pipeline from the serialized object.
  80841. */
  80842. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80843. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  80844. };
  80845. __decorate([
  80846. BABYLON.serialize()
  80847. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  80848. __decorate([
  80849. BABYLON.serialize()
  80850. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  80851. __decorate([
  80852. BABYLON.serialize()
  80853. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  80854. __decorate([
  80855. BABYLON.serialize()
  80856. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  80857. __decorate([
  80858. BABYLON.serialize()
  80859. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  80860. __decorate([
  80861. BABYLON.serialize()
  80862. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  80863. __decorate([
  80864. BABYLON.serialize()
  80865. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  80866. __decorate([
  80867. BABYLON.serialize()
  80868. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  80869. __decorate([
  80870. BABYLON.serialize()
  80871. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  80872. __decorate([
  80873. BABYLON.serialize()
  80874. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  80875. __decorate([
  80876. BABYLON.serialize()
  80877. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  80878. __decorate([
  80879. BABYLON.serialize()
  80880. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  80881. __decorate([
  80882. BABYLON.serialize()
  80883. ], DefaultRenderingPipeline.prototype, "samples", null);
  80884. __decorate([
  80885. BABYLON.serialize()
  80886. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  80887. __decorate([
  80888. BABYLON.serialize()
  80889. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  80890. __decorate([
  80891. BABYLON.serialize()
  80892. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  80893. __decorate([
  80894. BABYLON.serialize()
  80895. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  80896. return DefaultRenderingPipeline;
  80897. }(BABYLON.PostProcessRenderPipeline));
  80898. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  80899. })(BABYLON || (BABYLON = {}));
  80900. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  80901. var BABYLON;
  80902. (function (BABYLON) {
  80903. /**
  80904. * @hidden
  80905. */
  80906. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  80907. __extends(ImageProcessingConfigurationDefines, _super);
  80908. function ImageProcessingConfigurationDefines() {
  80909. var _this = _super.call(this) || this;
  80910. _this.IMAGEPROCESSING = false;
  80911. _this.VIGNETTE = false;
  80912. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80913. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80914. _this.TONEMAPPING = false;
  80915. _this.TONEMAPPING_ACES = false;
  80916. _this.CONTRAST = false;
  80917. _this.COLORCURVES = false;
  80918. _this.COLORGRADING = false;
  80919. _this.COLORGRADING3D = false;
  80920. _this.SAMPLER3DGREENDEPTH = false;
  80921. _this.SAMPLER3DBGRMAP = false;
  80922. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80923. _this.EXPOSURE = false;
  80924. _this.rebuild();
  80925. return _this;
  80926. }
  80927. return ImageProcessingConfigurationDefines;
  80928. }(BABYLON.MaterialDefines));
  80929. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80930. /**
  80931. * This groups together the common properties used for image processing either in direct forward pass
  80932. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80933. * or not.
  80934. */
  80935. var ImageProcessingConfiguration = /** @class */ (function () {
  80936. function ImageProcessingConfiguration() {
  80937. /**
  80938. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80939. */
  80940. this.colorCurves = new BABYLON.ColorCurves();
  80941. this._colorCurvesEnabled = false;
  80942. this._colorGradingEnabled = false;
  80943. this._colorGradingWithGreenDepth = true;
  80944. this._colorGradingBGR = true;
  80945. /** @hidden */
  80946. this._exposure = 1.0;
  80947. this._toneMappingEnabled = false;
  80948. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80949. this._contrast = 1.0;
  80950. /**
  80951. * Vignette stretch size.
  80952. */
  80953. this.vignetteStretch = 0;
  80954. /**
  80955. * Vignette centre X Offset.
  80956. */
  80957. this.vignetteCentreX = 0;
  80958. /**
  80959. * Vignette centre Y Offset.
  80960. */
  80961. this.vignetteCentreY = 0;
  80962. /**
  80963. * Vignette weight or intensity of the vignette effect.
  80964. */
  80965. this.vignetteWeight = 1.5;
  80966. /**
  80967. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80968. * if vignetteEnabled is set to true.
  80969. */
  80970. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80971. /**
  80972. * Camera field of view used by the Vignette effect.
  80973. */
  80974. this.vignetteCameraFov = 0.5;
  80975. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80976. this._vignetteEnabled = false;
  80977. this._applyByPostProcess = false;
  80978. this._isEnabled = true;
  80979. /**
  80980. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80981. */
  80982. this.onUpdateParameters = new BABYLON.Observable();
  80983. }
  80984. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80985. /**
  80986. * Gets wether the color curves effect is enabled.
  80987. */
  80988. get: function () {
  80989. return this._colorCurvesEnabled;
  80990. },
  80991. /**
  80992. * Sets wether the color curves effect is enabled.
  80993. */
  80994. set: function (value) {
  80995. if (this._colorCurvesEnabled === value) {
  80996. return;
  80997. }
  80998. this._colorCurvesEnabled = value;
  80999. this._updateParameters();
  81000. },
  81001. enumerable: true,
  81002. configurable: true
  81003. });
  81004. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  81005. /**
  81006. * Gets wether the color grading effect is enabled.
  81007. */
  81008. get: function () {
  81009. return this._colorGradingEnabled;
  81010. },
  81011. /**
  81012. * Sets wether the color grading effect is enabled.
  81013. */
  81014. set: function (value) {
  81015. if (this._colorGradingEnabled === value) {
  81016. return;
  81017. }
  81018. this._colorGradingEnabled = value;
  81019. this._updateParameters();
  81020. },
  81021. enumerable: true,
  81022. configurable: true
  81023. });
  81024. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  81025. /**
  81026. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  81027. */
  81028. get: function () {
  81029. return this._colorGradingWithGreenDepth;
  81030. },
  81031. /**
  81032. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  81033. */
  81034. set: function (value) {
  81035. if (this._colorGradingWithGreenDepth === value) {
  81036. return;
  81037. }
  81038. this._colorGradingWithGreenDepth = value;
  81039. this._updateParameters();
  81040. },
  81041. enumerable: true,
  81042. configurable: true
  81043. });
  81044. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  81045. /**
  81046. * Gets wether the color grading texture contains BGR values.
  81047. */
  81048. get: function () {
  81049. return this._colorGradingBGR;
  81050. },
  81051. /**
  81052. * Sets wether the color grading texture contains BGR values.
  81053. */
  81054. set: function (value) {
  81055. if (this._colorGradingBGR === value) {
  81056. return;
  81057. }
  81058. this._colorGradingBGR = value;
  81059. this._updateParameters();
  81060. },
  81061. enumerable: true,
  81062. configurable: true
  81063. });
  81064. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  81065. /**
  81066. * Gets the Exposure used in the effect.
  81067. */
  81068. get: function () {
  81069. return this._exposure;
  81070. },
  81071. /**
  81072. * Sets the Exposure used in the effect.
  81073. */
  81074. set: function (value) {
  81075. if (this._exposure === value) {
  81076. return;
  81077. }
  81078. this._exposure = value;
  81079. this._updateParameters();
  81080. },
  81081. enumerable: true,
  81082. configurable: true
  81083. });
  81084. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  81085. /**
  81086. * Gets wether the tone mapping effect is enabled.
  81087. */
  81088. get: function () {
  81089. return this._toneMappingEnabled;
  81090. },
  81091. /**
  81092. * Sets wether the tone mapping effect is enabled.
  81093. */
  81094. set: function (value) {
  81095. if (this._toneMappingEnabled === value) {
  81096. return;
  81097. }
  81098. this._toneMappingEnabled = value;
  81099. this._updateParameters();
  81100. },
  81101. enumerable: true,
  81102. configurable: true
  81103. });
  81104. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  81105. /**
  81106. * Gets the type of tone mapping effect.
  81107. */
  81108. get: function () {
  81109. return this._toneMappingType;
  81110. },
  81111. /**
  81112. * Sets the type of tone mapping effect used in BabylonJS.
  81113. */
  81114. set: function (value) {
  81115. if (this._toneMappingType === value) {
  81116. return;
  81117. }
  81118. this._toneMappingType = value;
  81119. this._updateParameters();
  81120. },
  81121. enumerable: true,
  81122. configurable: true
  81123. });
  81124. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  81125. /**
  81126. * Gets the contrast used in the effect.
  81127. */
  81128. get: function () {
  81129. return this._contrast;
  81130. },
  81131. /**
  81132. * Sets the contrast used in the effect.
  81133. */
  81134. set: function (value) {
  81135. if (this._contrast === value) {
  81136. return;
  81137. }
  81138. this._contrast = value;
  81139. this._updateParameters();
  81140. },
  81141. enumerable: true,
  81142. configurable: true
  81143. });
  81144. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  81145. /**
  81146. * Gets the vignette blend mode allowing different kind of effect.
  81147. */
  81148. get: function () {
  81149. return this._vignetteBlendMode;
  81150. },
  81151. /**
  81152. * Sets the vignette blend mode allowing different kind of effect.
  81153. */
  81154. set: function (value) {
  81155. if (this._vignetteBlendMode === value) {
  81156. return;
  81157. }
  81158. this._vignetteBlendMode = value;
  81159. this._updateParameters();
  81160. },
  81161. enumerable: true,
  81162. configurable: true
  81163. });
  81164. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  81165. /**
  81166. * Gets wether the vignette effect is enabled.
  81167. */
  81168. get: function () {
  81169. return this._vignetteEnabled;
  81170. },
  81171. /**
  81172. * Sets wether the vignette effect is enabled.
  81173. */
  81174. set: function (value) {
  81175. if (this._vignetteEnabled === value) {
  81176. return;
  81177. }
  81178. this._vignetteEnabled = value;
  81179. this._updateParameters();
  81180. },
  81181. enumerable: true,
  81182. configurable: true
  81183. });
  81184. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  81185. /**
  81186. * Gets wether the image processing is applied through a post process or not.
  81187. */
  81188. get: function () {
  81189. return this._applyByPostProcess;
  81190. },
  81191. /**
  81192. * Sets wether the image processing is applied through a post process or not.
  81193. */
  81194. set: function (value) {
  81195. if (this._applyByPostProcess === value) {
  81196. return;
  81197. }
  81198. this._applyByPostProcess = value;
  81199. this._updateParameters();
  81200. },
  81201. enumerable: true,
  81202. configurable: true
  81203. });
  81204. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  81205. /**
  81206. * Gets wether the image processing is enabled or not.
  81207. */
  81208. get: function () {
  81209. return this._isEnabled;
  81210. },
  81211. /**
  81212. * Sets wether the image processing is enabled or not.
  81213. */
  81214. set: function (value) {
  81215. if (this._isEnabled === value) {
  81216. return;
  81217. }
  81218. this._isEnabled = value;
  81219. this._updateParameters();
  81220. },
  81221. enumerable: true,
  81222. configurable: true
  81223. });
  81224. /**
  81225. * Method called each time the image processing information changes requires to recompile the effect.
  81226. */
  81227. ImageProcessingConfiguration.prototype._updateParameters = function () {
  81228. this.onUpdateParameters.notifyObservers(this);
  81229. };
  81230. ImageProcessingConfiguration.prototype.getClassName = function () {
  81231. return "ImageProcessingConfiguration";
  81232. };
  81233. /**
  81234. * Prepare the list of uniforms associated with the Image Processing effects.
  81235. * @param uniformsList The list of uniforms used in the effect
  81236. * @param defines the list of defines currently in use
  81237. */
  81238. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  81239. if (defines.EXPOSURE) {
  81240. uniforms.push("exposureLinear");
  81241. }
  81242. if (defines.CONTRAST) {
  81243. uniforms.push("contrast");
  81244. }
  81245. if (defines.COLORGRADING) {
  81246. uniforms.push("colorTransformSettings");
  81247. }
  81248. if (defines.VIGNETTE) {
  81249. uniforms.push("vInverseScreenSize");
  81250. uniforms.push("vignetteSettings1");
  81251. uniforms.push("vignetteSettings2");
  81252. }
  81253. if (defines.COLORCURVES) {
  81254. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  81255. }
  81256. };
  81257. /**
  81258. * Prepare the list of samplers associated with the Image Processing effects.
  81259. * @param uniformsList The list of uniforms used in the effect
  81260. * @param defines the list of defines currently in use
  81261. */
  81262. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  81263. if (defines.COLORGRADING) {
  81264. samplersList.push("txColorTransform");
  81265. }
  81266. };
  81267. /**
  81268. * Prepare the list of defines associated to the shader.
  81269. * @param defines the list of defines to complete
  81270. */
  81271. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  81272. if (forPostProcess === void 0) { forPostProcess = false; }
  81273. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  81274. defines.VIGNETTE = false;
  81275. defines.TONEMAPPING = false;
  81276. defines.TONEMAPPING_ACES = false;
  81277. defines.CONTRAST = false;
  81278. defines.EXPOSURE = false;
  81279. defines.COLORCURVES = false;
  81280. defines.COLORGRADING = false;
  81281. defines.COLORGRADING3D = false;
  81282. defines.IMAGEPROCESSING = false;
  81283. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  81284. return;
  81285. }
  81286. defines.VIGNETTE = this.vignetteEnabled;
  81287. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  81288. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  81289. defines.TONEMAPPING = this.toneMappingEnabled;
  81290. switch (this._toneMappingType) {
  81291. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  81292. defines.TONEMAPPING_ACES = true;
  81293. break;
  81294. }
  81295. defines.CONTRAST = (this.contrast !== 1.0);
  81296. defines.EXPOSURE = (this.exposure !== 1.0);
  81297. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  81298. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  81299. if (defines.COLORGRADING) {
  81300. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  81301. }
  81302. else {
  81303. defines.COLORGRADING3D = false;
  81304. }
  81305. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  81306. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  81307. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  81308. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  81309. };
  81310. /**
  81311. * Returns true if all the image processing information are ready.
  81312. */
  81313. ImageProcessingConfiguration.prototype.isReady = function () {
  81314. // Color Grading texure can not be none blocking.
  81315. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  81316. };
  81317. /**
  81318. * Binds the image processing to the shader.
  81319. * @param effect The effect to bind to
  81320. */
  81321. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  81322. if (aspectRatio === void 0) { aspectRatio = 1; }
  81323. // Color Curves
  81324. if (this._colorCurvesEnabled && this.colorCurves) {
  81325. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  81326. }
  81327. // Vignette
  81328. if (this._vignetteEnabled) {
  81329. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  81330. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  81331. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  81332. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  81333. var vignetteScaleX = vignetteScaleY * aspectRatio;
  81334. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  81335. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  81336. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  81337. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  81338. var vignettePower = -2.0 * this.vignetteWeight;
  81339. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  81340. }
  81341. // Exposure
  81342. effect.setFloat("exposureLinear", this.exposure);
  81343. // Contrast
  81344. effect.setFloat("contrast", this.contrast);
  81345. // Color transform settings
  81346. if (this.colorGradingTexture) {
  81347. effect.setTexture("txColorTransform", this.colorGradingTexture);
  81348. var textureSize = this.colorGradingTexture.getSize().height;
  81349. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  81350. 0.5 / textureSize, // textureOffset
  81351. textureSize, // textureSize
  81352. this.colorGradingTexture.level // weight
  81353. );
  81354. }
  81355. };
  81356. /**
  81357. * Clones the current image processing instance.
  81358. * @return The cloned image processing
  81359. */
  81360. ImageProcessingConfiguration.prototype.clone = function () {
  81361. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  81362. };
  81363. /**
  81364. * Serializes the current image processing instance to a json representation.
  81365. * @return a JSON representation
  81366. */
  81367. ImageProcessingConfiguration.prototype.serialize = function () {
  81368. return BABYLON.SerializationHelper.Serialize(this);
  81369. };
  81370. /**
  81371. * Parses the image processing from a json representation.
  81372. * @param source the JSON source to parse
  81373. * @return The parsed image processing
  81374. */
  81375. ImageProcessingConfiguration.Parse = function (source) {
  81376. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  81377. };
  81378. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  81379. /**
  81380. * Used to apply the vignette as a mix with the pixel color.
  81381. */
  81382. get: function () {
  81383. return this._VIGNETTEMODE_MULTIPLY;
  81384. },
  81385. enumerable: true,
  81386. configurable: true
  81387. });
  81388. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  81389. /**
  81390. * Used to apply the vignette as a replacement of the pixel color.
  81391. */
  81392. get: function () {
  81393. return this._VIGNETTEMODE_OPAQUE;
  81394. },
  81395. enumerable: true,
  81396. configurable: true
  81397. });
  81398. /**
  81399. * Default tone mapping applied in BabylonJS.
  81400. */
  81401. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  81402. /**
  81403. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  81404. * to other engines rendering to increase portability.
  81405. */
  81406. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  81407. // Static constants associated to the image processing.
  81408. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  81409. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  81410. __decorate([
  81411. BABYLON.serializeAsColorCurves()
  81412. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  81413. __decorate([
  81414. BABYLON.serialize()
  81415. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  81416. __decorate([
  81417. BABYLON.serializeAsTexture()
  81418. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  81419. __decorate([
  81420. BABYLON.serialize()
  81421. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  81422. __decorate([
  81423. BABYLON.serialize()
  81424. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  81425. __decorate([
  81426. BABYLON.serialize()
  81427. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  81428. __decorate([
  81429. BABYLON.serialize()
  81430. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  81431. __decorate([
  81432. BABYLON.serialize()
  81433. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  81434. __decorate([
  81435. BABYLON.serialize()
  81436. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  81437. __decorate([
  81438. BABYLON.serialize()
  81439. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  81440. __decorate([
  81441. BABYLON.serialize()
  81442. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  81443. __decorate([
  81444. BABYLON.serialize()
  81445. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  81446. __decorate([
  81447. BABYLON.serialize()
  81448. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  81449. __decorate([
  81450. BABYLON.serialize()
  81451. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  81452. __decorate([
  81453. BABYLON.serializeAsColor4()
  81454. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  81455. __decorate([
  81456. BABYLON.serialize()
  81457. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  81458. __decorate([
  81459. BABYLON.serialize()
  81460. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  81461. __decorate([
  81462. BABYLON.serialize()
  81463. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  81464. __decorate([
  81465. BABYLON.serialize()
  81466. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  81467. __decorate([
  81468. BABYLON.serialize()
  81469. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  81470. return ImageProcessingConfiguration;
  81471. }());
  81472. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  81473. })(BABYLON || (BABYLON = {}));
  81474. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  81475. var BABYLON;
  81476. (function (BABYLON) {
  81477. /**
  81478. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  81479. * It can help converting any input color in a desired output one. This can then be used to create effects
  81480. * from sepia, black and white to sixties or futuristic rendering...
  81481. *
  81482. * The only supported format is currently 3dl.
  81483. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  81484. */
  81485. var ColorGradingTexture = /** @class */ (function (_super) {
  81486. __extends(ColorGradingTexture, _super);
  81487. /**
  81488. * Instantiates a ColorGradingTexture from the following parameters.
  81489. *
  81490. * @param url The location of the color gradind data (currently only supporting 3dl)
  81491. * @param scene The scene the texture will be used in
  81492. */
  81493. function ColorGradingTexture(url, scene) {
  81494. var _this = _super.call(this, scene) || this;
  81495. if (!url) {
  81496. return _this;
  81497. }
  81498. _this._engine = scene.getEngine();
  81499. _this._textureMatrix = BABYLON.Matrix.Identity();
  81500. _this.name = url;
  81501. _this.url = url;
  81502. _this.hasAlpha = false;
  81503. _this.isCube = false;
  81504. _this.is3D = _this._engine.webGLVersion > 1;
  81505. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81506. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81507. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81508. _this.anisotropicFilteringLevel = 1;
  81509. _this._texture = _this._getFromCache(url, true);
  81510. if (!_this._texture) {
  81511. if (!scene.useDelayedTextureLoading) {
  81512. _this.loadTexture();
  81513. }
  81514. else {
  81515. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81516. }
  81517. }
  81518. return _this;
  81519. }
  81520. /**
  81521. * Returns the texture matrix used in most of the material.
  81522. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  81523. */
  81524. ColorGradingTexture.prototype.getTextureMatrix = function () {
  81525. return this._textureMatrix;
  81526. };
  81527. /**
  81528. * Occurs when the file being loaded is a .3dl LUT file.
  81529. */
  81530. ColorGradingTexture.prototype.load3dlTexture = function () {
  81531. var engine = this._engine;
  81532. var texture;
  81533. if (engine.webGLVersion === 1) {
  81534. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81535. }
  81536. else {
  81537. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81538. }
  81539. this._texture = texture;
  81540. var callback = function (text) {
  81541. if (typeof text !== "string") {
  81542. return;
  81543. }
  81544. var data = null;
  81545. var tempData = null;
  81546. var line;
  81547. var lines = text.split('\n');
  81548. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  81549. var maxColor = 0;
  81550. for (var i = 0; i < lines.length; i++) {
  81551. line = lines[i];
  81552. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  81553. continue;
  81554. if (line.indexOf('#') === 0)
  81555. continue;
  81556. var words = line.split(" ");
  81557. if (size === 0) {
  81558. // Number of space + one
  81559. size = words.length;
  81560. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  81561. tempData = new Float32Array(size * size * size * 4);
  81562. continue;
  81563. }
  81564. if (size != 0) {
  81565. var r = Math.max(parseInt(words[0]), 0);
  81566. var g = Math.max(parseInt(words[1]), 0);
  81567. var b = Math.max(parseInt(words[2]), 0);
  81568. maxColor = Math.max(r, maxColor);
  81569. maxColor = Math.max(g, maxColor);
  81570. maxColor = Math.max(b, maxColor);
  81571. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  81572. if (tempData) {
  81573. tempData[pixelStorageIndex + 0] = r;
  81574. tempData[pixelStorageIndex + 1] = g;
  81575. tempData[pixelStorageIndex + 2] = b;
  81576. }
  81577. pixelIndexSlice++;
  81578. if (pixelIndexSlice % size == 0) {
  81579. pixelIndexH++;
  81580. pixelIndexSlice = 0;
  81581. if (pixelIndexH % size == 0) {
  81582. pixelIndexW++;
  81583. pixelIndexH = 0;
  81584. }
  81585. }
  81586. }
  81587. }
  81588. if (tempData && data) {
  81589. for (var i = 0; i < tempData.length; i++) {
  81590. if (i > 0 && (i + 1) % 4 === 0) {
  81591. data[i] = 255;
  81592. }
  81593. else {
  81594. var value = tempData[i];
  81595. data[i] = (value / maxColor * 255);
  81596. }
  81597. }
  81598. }
  81599. if (texture.is3D) {
  81600. texture.updateSize(size, size, size);
  81601. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81602. }
  81603. else {
  81604. texture.updateSize(size * size, size);
  81605. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81606. }
  81607. };
  81608. var scene = this.getScene();
  81609. if (scene) {
  81610. scene._loadFile(this.url, callback);
  81611. }
  81612. else {
  81613. this._engine._loadFile(this.url, callback);
  81614. }
  81615. return this._texture;
  81616. };
  81617. /**
  81618. * Starts the loading process of the texture.
  81619. */
  81620. ColorGradingTexture.prototype.loadTexture = function () {
  81621. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  81622. this.load3dlTexture();
  81623. }
  81624. };
  81625. /**
  81626. * Clones the color gradind texture.
  81627. */
  81628. ColorGradingTexture.prototype.clone = function () {
  81629. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  81630. // Base texture
  81631. newTexture.level = this.level;
  81632. return newTexture;
  81633. };
  81634. /**
  81635. * Called during delayed load for textures.
  81636. */
  81637. ColorGradingTexture.prototype.delayLoad = function () {
  81638. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81639. return;
  81640. }
  81641. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81642. this._texture = this._getFromCache(this.url, true);
  81643. if (!this._texture) {
  81644. this.loadTexture();
  81645. }
  81646. };
  81647. /**
  81648. * Parses a color grading texture serialized by Babylon.
  81649. * @param parsedTexture The texture information being parsedTexture
  81650. * @param scene The scene to load the texture in
  81651. * @param rootUrl The root url of the data assets to load
  81652. * @return A color gradind texture
  81653. */
  81654. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81655. var texture = null;
  81656. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81657. texture = new ColorGradingTexture(parsedTexture.name, scene);
  81658. texture.name = parsedTexture.name;
  81659. texture.level = parsedTexture.level;
  81660. }
  81661. return texture;
  81662. };
  81663. /**
  81664. * Serializes the LUT texture to json format.
  81665. */
  81666. ColorGradingTexture.prototype.serialize = function () {
  81667. if (!this.name) {
  81668. return null;
  81669. }
  81670. var serializationObject = {};
  81671. serializationObject.name = this.name;
  81672. serializationObject.level = this.level;
  81673. serializationObject.customType = "BABYLON.ColorGradingTexture";
  81674. return serializationObject;
  81675. };
  81676. /**
  81677. * Empty line regex stored for GC.
  81678. */
  81679. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  81680. return ColorGradingTexture;
  81681. }(BABYLON.BaseTexture));
  81682. BABYLON.ColorGradingTexture = ColorGradingTexture;
  81683. })(BABYLON || (BABYLON = {}));
  81684. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  81685. var BABYLON;
  81686. (function (BABYLON) {
  81687. /**
  81688. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81689. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81690. * 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;
  81691. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81692. */
  81693. var ColorCurves = /** @class */ (function () {
  81694. function ColorCurves() {
  81695. this._dirty = true;
  81696. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81697. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81698. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81699. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81700. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81701. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81702. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81703. this._globalHue = 30;
  81704. this._globalDensity = 0;
  81705. this._globalSaturation = 0;
  81706. this._globalExposure = 0;
  81707. this._highlightsHue = 30;
  81708. this._highlightsDensity = 0;
  81709. this._highlightsSaturation = 0;
  81710. this._highlightsExposure = 0;
  81711. this._midtonesHue = 30;
  81712. this._midtonesDensity = 0;
  81713. this._midtonesSaturation = 0;
  81714. this._midtonesExposure = 0;
  81715. this._shadowsHue = 30;
  81716. this._shadowsDensity = 0;
  81717. this._shadowsSaturation = 0;
  81718. this._shadowsExposure = 0;
  81719. }
  81720. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81721. /**
  81722. * Gets the global Hue value.
  81723. * 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).
  81724. */
  81725. get: function () {
  81726. return this._globalHue;
  81727. },
  81728. /**
  81729. * Sets the global Hue value.
  81730. * 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).
  81731. */
  81732. set: function (value) {
  81733. this._globalHue = value;
  81734. this._dirty = true;
  81735. },
  81736. enumerable: true,
  81737. configurable: true
  81738. });
  81739. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81740. /**
  81741. * Gets the global Density value.
  81742. * 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.
  81743. * Values less than zero provide a filter of opposite hue.
  81744. */
  81745. get: function () {
  81746. return this._globalDensity;
  81747. },
  81748. /**
  81749. * Sets the global Density value.
  81750. * 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.
  81751. * Values less than zero provide a filter of opposite hue.
  81752. */
  81753. set: function (value) {
  81754. this._globalDensity = value;
  81755. this._dirty = true;
  81756. },
  81757. enumerable: true,
  81758. configurable: true
  81759. });
  81760. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81761. /**
  81762. * Gets the global Saturation value.
  81763. * 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.
  81764. */
  81765. get: function () {
  81766. return this._globalSaturation;
  81767. },
  81768. /**
  81769. * Sets the global Saturation value.
  81770. * 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.
  81771. */
  81772. set: function (value) {
  81773. this._globalSaturation = value;
  81774. this._dirty = true;
  81775. },
  81776. enumerable: true,
  81777. configurable: true
  81778. });
  81779. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  81780. /**
  81781. * Gets the global Exposure value.
  81782. * 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.
  81783. */
  81784. get: function () {
  81785. return this._globalExposure;
  81786. },
  81787. /**
  81788. * Sets the global Exposure value.
  81789. * 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.
  81790. */
  81791. set: function (value) {
  81792. this._globalExposure = value;
  81793. this._dirty = true;
  81794. },
  81795. enumerable: true,
  81796. configurable: true
  81797. });
  81798. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  81799. /**
  81800. * Gets the highlights Hue value.
  81801. * 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).
  81802. */
  81803. get: function () {
  81804. return this._highlightsHue;
  81805. },
  81806. /**
  81807. * Sets the highlights Hue value.
  81808. * 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).
  81809. */
  81810. set: function (value) {
  81811. this._highlightsHue = value;
  81812. this._dirty = true;
  81813. },
  81814. enumerable: true,
  81815. configurable: true
  81816. });
  81817. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  81818. /**
  81819. * Gets the highlights Density value.
  81820. * 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.
  81821. * Values less than zero provide a filter of opposite hue.
  81822. */
  81823. get: function () {
  81824. return this._highlightsDensity;
  81825. },
  81826. /**
  81827. * Sets the highlights Density value.
  81828. * 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.
  81829. * Values less than zero provide a filter of opposite hue.
  81830. */
  81831. set: function (value) {
  81832. this._highlightsDensity = value;
  81833. this._dirty = true;
  81834. },
  81835. enumerable: true,
  81836. configurable: true
  81837. });
  81838. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  81839. /**
  81840. * Gets the highlights Saturation value.
  81841. * 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.
  81842. */
  81843. get: function () {
  81844. return this._highlightsSaturation;
  81845. },
  81846. /**
  81847. * Sets the highlights Saturation value.
  81848. * 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.
  81849. */
  81850. set: function (value) {
  81851. this._highlightsSaturation = value;
  81852. this._dirty = true;
  81853. },
  81854. enumerable: true,
  81855. configurable: true
  81856. });
  81857. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  81858. /**
  81859. * Gets the highlights Exposure value.
  81860. * 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.
  81861. */
  81862. get: function () {
  81863. return this._highlightsExposure;
  81864. },
  81865. /**
  81866. * Sets the highlights Exposure value.
  81867. * 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.
  81868. */
  81869. set: function (value) {
  81870. this._highlightsExposure = value;
  81871. this._dirty = true;
  81872. },
  81873. enumerable: true,
  81874. configurable: true
  81875. });
  81876. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  81877. /**
  81878. * Gets the midtones Hue value.
  81879. * 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).
  81880. */
  81881. get: function () {
  81882. return this._midtonesHue;
  81883. },
  81884. /**
  81885. * Sets the midtones Hue value.
  81886. * 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).
  81887. */
  81888. set: function (value) {
  81889. this._midtonesHue = value;
  81890. this._dirty = true;
  81891. },
  81892. enumerable: true,
  81893. configurable: true
  81894. });
  81895. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  81896. /**
  81897. * Gets the midtones Density value.
  81898. * 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.
  81899. * Values less than zero provide a filter of opposite hue.
  81900. */
  81901. get: function () {
  81902. return this._midtonesDensity;
  81903. },
  81904. /**
  81905. * Sets the midtones Density value.
  81906. * 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.
  81907. * Values less than zero provide a filter of opposite hue.
  81908. */
  81909. set: function (value) {
  81910. this._midtonesDensity = value;
  81911. this._dirty = true;
  81912. },
  81913. enumerable: true,
  81914. configurable: true
  81915. });
  81916. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81917. /**
  81918. * Gets the midtones Saturation value.
  81919. * 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.
  81920. */
  81921. get: function () {
  81922. return this._midtonesSaturation;
  81923. },
  81924. /**
  81925. * Sets the midtones Saturation value.
  81926. * 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.
  81927. */
  81928. set: function (value) {
  81929. this._midtonesSaturation = value;
  81930. this._dirty = true;
  81931. },
  81932. enumerable: true,
  81933. configurable: true
  81934. });
  81935. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81936. /**
  81937. * Gets the midtones Exposure value.
  81938. * 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.
  81939. */
  81940. get: function () {
  81941. return this._midtonesExposure;
  81942. },
  81943. /**
  81944. * Sets the midtones Exposure value.
  81945. * 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.
  81946. */
  81947. set: function (value) {
  81948. this._midtonesExposure = value;
  81949. this._dirty = true;
  81950. },
  81951. enumerable: true,
  81952. configurable: true
  81953. });
  81954. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81955. /**
  81956. * Gets the shadows Hue value.
  81957. * 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).
  81958. */
  81959. get: function () {
  81960. return this._shadowsHue;
  81961. },
  81962. /**
  81963. * Sets the shadows Hue value.
  81964. * 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).
  81965. */
  81966. set: function (value) {
  81967. this._shadowsHue = value;
  81968. this._dirty = true;
  81969. },
  81970. enumerable: true,
  81971. configurable: true
  81972. });
  81973. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81974. /**
  81975. * Gets the shadows Density value.
  81976. * 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.
  81977. * Values less than zero provide a filter of opposite hue.
  81978. */
  81979. get: function () {
  81980. return this._shadowsDensity;
  81981. },
  81982. /**
  81983. * Sets the shadows Density value.
  81984. * 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.
  81985. * Values less than zero provide a filter of opposite hue.
  81986. */
  81987. set: function (value) {
  81988. this._shadowsDensity = value;
  81989. this._dirty = true;
  81990. },
  81991. enumerable: true,
  81992. configurable: true
  81993. });
  81994. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81995. /**
  81996. * Gets the shadows Saturation value.
  81997. * 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.
  81998. */
  81999. get: function () {
  82000. return this._shadowsSaturation;
  82001. },
  82002. /**
  82003. * Sets the shadows Saturation value.
  82004. * 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.
  82005. */
  82006. set: function (value) {
  82007. this._shadowsSaturation = value;
  82008. this._dirty = true;
  82009. },
  82010. enumerable: true,
  82011. configurable: true
  82012. });
  82013. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  82014. /**
  82015. * Gets the shadows Exposure value.
  82016. * 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.
  82017. */
  82018. get: function () {
  82019. return this._shadowsExposure;
  82020. },
  82021. /**
  82022. * Sets the shadows Exposure value.
  82023. * 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.
  82024. */
  82025. set: function (value) {
  82026. this._shadowsExposure = value;
  82027. this._dirty = true;
  82028. },
  82029. enumerable: true,
  82030. configurable: true
  82031. });
  82032. ColorCurves.prototype.getClassName = function () {
  82033. return "ColorCurves";
  82034. };
  82035. /**
  82036. * Binds the color curves to the shader.
  82037. * @param colorCurves The color curve to bind
  82038. * @param effect The effect to bind to
  82039. */
  82040. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  82041. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  82042. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  82043. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  82044. if (colorCurves._dirty) {
  82045. colorCurves._dirty = false;
  82046. // Fill in global info.
  82047. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  82048. // Compute highlights info.
  82049. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  82050. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  82051. // Compute midtones info.
  82052. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  82053. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  82054. // Compute shadows info.
  82055. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  82056. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  82057. // Compute deltas (neutral is midtones).
  82058. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  82059. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  82060. }
  82061. if (effect) {
  82062. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  82063. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  82064. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  82065. }
  82066. };
  82067. /**
  82068. * Prepare the list of uniforms associated with the ColorCurves effects.
  82069. * @param uniformsList The list of uniforms used in the effect
  82070. */
  82071. ColorCurves.PrepareUniforms = function (uniformsList) {
  82072. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  82073. };
  82074. /**
  82075. * Returns color grading data based on a hue, density, saturation and exposure value.
  82076. * @param filterHue The hue of the color filter.
  82077. * @param filterDensity The density of the color filter.
  82078. * @param saturation The saturation.
  82079. * @param exposure The exposure.
  82080. * @param result The result data container.
  82081. */
  82082. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  82083. if (hue == null) {
  82084. return;
  82085. }
  82086. hue = ColorCurves.clamp(hue, 0, 360);
  82087. density = ColorCurves.clamp(density, -100, 100);
  82088. saturation = ColorCurves.clamp(saturation, -100, 100);
  82089. exposure = ColorCurves.clamp(exposure, -100, 100);
  82090. // Remap the slider/config filter density with non-linear mapping and also scale by half
  82091. // so that the maximum filter density is only 50% control. This provides fine control
  82092. // for small values and reasonable range.
  82093. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  82094. density *= 0.5;
  82095. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  82096. if (density < 0) {
  82097. density *= -1;
  82098. hue = (hue + 180) % 360;
  82099. }
  82100. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  82101. result.scaleToRef(2, result);
  82102. result.a = 1 + 0.01 * saturation;
  82103. };
  82104. /**
  82105. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  82106. * @param value The input slider value in range [-100,100].
  82107. * @returns Adjusted value.
  82108. */
  82109. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  82110. value /= 100;
  82111. var x = Math.abs(value);
  82112. x = Math.pow(x, 2);
  82113. if (value < 0) {
  82114. x *= -1;
  82115. }
  82116. x *= 100;
  82117. return x;
  82118. };
  82119. /**
  82120. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  82121. * @param hue The hue (H) input.
  82122. * @param saturation The saturation (S) input.
  82123. * @param brightness The brightness (B) input.
  82124. * @result An RGBA color represented as Vector4.
  82125. */
  82126. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  82127. var h = ColorCurves.clamp(hue, 0, 360);
  82128. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  82129. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  82130. if (s === 0) {
  82131. result.r = v;
  82132. result.g = v;
  82133. result.b = v;
  82134. }
  82135. else {
  82136. // sector 0 to 5
  82137. h /= 60;
  82138. var i = Math.floor(h);
  82139. // fractional part of h
  82140. var f = h - i;
  82141. var p = v * (1 - s);
  82142. var q = v * (1 - s * f);
  82143. var t = v * (1 - s * (1 - f));
  82144. switch (i) {
  82145. case 0:
  82146. result.r = v;
  82147. result.g = t;
  82148. result.b = p;
  82149. break;
  82150. case 1:
  82151. result.r = q;
  82152. result.g = v;
  82153. result.b = p;
  82154. break;
  82155. case 2:
  82156. result.r = p;
  82157. result.g = v;
  82158. result.b = t;
  82159. break;
  82160. case 3:
  82161. result.r = p;
  82162. result.g = q;
  82163. result.b = v;
  82164. break;
  82165. case 4:
  82166. result.r = t;
  82167. result.g = p;
  82168. result.b = v;
  82169. break;
  82170. default: // case 5:
  82171. result.r = v;
  82172. result.g = p;
  82173. result.b = q;
  82174. break;
  82175. }
  82176. }
  82177. result.a = 1;
  82178. };
  82179. /**
  82180. * Returns a value clamped between min and max
  82181. * @param value The value to clamp
  82182. * @param min The minimum of value
  82183. * @param max The maximum of value
  82184. * @returns The clamped value.
  82185. */
  82186. ColorCurves.clamp = function (value, min, max) {
  82187. return Math.min(Math.max(value, min), max);
  82188. };
  82189. /**
  82190. * Clones the current color curve instance.
  82191. * @return The cloned curves
  82192. */
  82193. ColorCurves.prototype.clone = function () {
  82194. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  82195. };
  82196. /**
  82197. * Serializes the current color curve instance to a json representation.
  82198. * @return a JSON representation
  82199. */
  82200. ColorCurves.prototype.serialize = function () {
  82201. return BABYLON.SerializationHelper.Serialize(this);
  82202. };
  82203. /**
  82204. * Parses the color curve from a json representation.
  82205. * @param source the JSON source to parse
  82206. * @return The parsed curves
  82207. */
  82208. ColorCurves.Parse = function (source) {
  82209. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  82210. };
  82211. __decorate([
  82212. BABYLON.serialize()
  82213. ], ColorCurves.prototype, "_globalHue", void 0);
  82214. __decorate([
  82215. BABYLON.serialize()
  82216. ], ColorCurves.prototype, "_globalDensity", void 0);
  82217. __decorate([
  82218. BABYLON.serialize()
  82219. ], ColorCurves.prototype, "_globalSaturation", void 0);
  82220. __decorate([
  82221. BABYLON.serialize()
  82222. ], ColorCurves.prototype, "_globalExposure", void 0);
  82223. __decorate([
  82224. BABYLON.serialize()
  82225. ], ColorCurves.prototype, "_highlightsHue", void 0);
  82226. __decorate([
  82227. BABYLON.serialize()
  82228. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  82229. __decorate([
  82230. BABYLON.serialize()
  82231. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  82232. __decorate([
  82233. BABYLON.serialize()
  82234. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  82235. __decorate([
  82236. BABYLON.serialize()
  82237. ], ColorCurves.prototype, "_midtonesHue", void 0);
  82238. __decorate([
  82239. BABYLON.serialize()
  82240. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  82241. __decorate([
  82242. BABYLON.serialize()
  82243. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  82244. __decorate([
  82245. BABYLON.serialize()
  82246. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  82247. return ColorCurves;
  82248. }());
  82249. BABYLON.ColorCurves = ColorCurves;
  82250. })(BABYLON || (BABYLON = {}));
  82251. //# sourceMappingURL=babylon.colorCurves.js.map
  82252. var BABYLON;
  82253. (function (BABYLON) {
  82254. var RefractionPostProcess = /** @class */ (function (_super) {
  82255. __extends(RefractionPostProcess, _super);
  82256. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  82257. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  82258. _this.color = color;
  82259. _this.depth = depth;
  82260. _this.colorLevel = colorLevel;
  82261. _this._ownRefractionTexture = true;
  82262. _this.onActivateObservable.add(function (cam) {
  82263. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  82264. });
  82265. _this.onApplyObservable.add(function (effect) {
  82266. effect.setColor3("baseColor", _this.color);
  82267. effect.setFloat("depth", _this.depth);
  82268. effect.setFloat("colorLevel", _this.colorLevel);
  82269. effect.setTexture("refractionSampler", _this._refTexture);
  82270. });
  82271. return _this;
  82272. }
  82273. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  82274. /**
  82275. * Gets or sets the refraction texture
  82276. * Please note that you are responsible for disposing the texture if you set it manually
  82277. */
  82278. get: function () {
  82279. return this._refTexture;
  82280. },
  82281. set: function (value) {
  82282. if (this._refTexture && this._ownRefractionTexture) {
  82283. this._refTexture.dispose();
  82284. }
  82285. this._refTexture = value;
  82286. this._ownRefractionTexture = false;
  82287. },
  82288. enumerable: true,
  82289. configurable: true
  82290. });
  82291. // Methods
  82292. RefractionPostProcess.prototype.dispose = function (camera) {
  82293. if (this._refTexture && this._ownRefractionTexture) {
  82294. this._refTexture.dispose();
  82295. this._refTexture = null;
  82296. }
  82297. _super.prototype.dispose.call(this, camera);
  82298. };
  82299. return RefractionPostProcess;
  82300. }(BABYLON.PostProcess));
  82301. BABYLON.RefractionPostProcess = RefractionPostProcess;
  82302. })(BABYLON || (BABYLON = {}));
  82303. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  82304. var BABYLON;
  82305. (function (BABYLON) {
  82306. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  82307. __extends(BlackAndWhitePostProcess, _super);
  82308. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  82309. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  82310. _this.degree = 1;
  82311. _this.onApplyObservable.add(function (effect) {
  82312. effect.setFloat("degree", _this.degree);
  82313. });
  82314. return _this;
  82315. }
  82316. return BlackAndWhitePostProcess;
  82317. }(BABYLON.PostProcess));
  82318. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  82319. })(BABYLON || (BABYLON = {}));
  82320. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  82321. var BABYLON;
  82322. (function (BABYLON) {
  82323. /**
  82324. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  82325. * input texture to perform effects such as edge detection or sharpening
  82326. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82327. */
  82328. var ConvolutionPostProcess = /** @class */ (function (_super) {
  82329. __extends(ConvolutionPostProcess, _super);
  82330. /**
  82331. * Creates a new instance ConvolutionPostProcess
  82332. * @param name The name of the effect.
  82333. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  82334. * @param options The required width/height ratio to downsize to before computing the render pass.
  82335. * @param camera The camera to apply the render pass to.
  82336. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82337. * @param engine The engine which the post process will be applied. (default: current engine)
  82338. * @param reusable If the post process can be reused on the same frame. (default: false)
  82339. * @param textureType Type of textures used when performing the post process. (default: 0)
  82340. */
  82341. function ConvolutionPostProcess(name,
  82342. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  82343. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  82344. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82345. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82346. _this.kernel = kernel;
  82347. _this.onApply = function (effect) {
  82348. effect.setFloat2("screenSize", _this.width, _this.height);
  82349. effect.setArray("kernel", _this.kernel);
  82350. };
  82351. return _this;
  82352. }
  82353. // Statics
  82354. /**
  82355. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82356. */
  82357. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  82358. /**
  82359. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82360. */
  82361. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  82362. /**
  82363. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82364. */
  82365. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  82366. /**
  82367. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82368. */
  82369. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  82370. /**
  82371. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82372. */
  82373. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  82374. /**
  82375. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82376. */
  82377. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  82378. return ConvolutionPostProcess;
  82379. }(BABYLON.PostProcess));
  82380. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  82381. })(BABYLON || (BABYLON = {}));
  82382. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  82383. var BABYLON;
  82384. (function (BABYLON) {
  82385. var FilterPostProcess = /** @class */ (function (_super) {
  82386. __extends(FilterPostProcess, _super);
  82387. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  82388. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  82389. _this.kernelMatrix = kernelMatrix;
  82390. _this.onApply = function (effect) {
  82391. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  82392. };
  82393. return _this;
  82394. }
  82395. return FilterPostProcess;
  82396. }(BABYLON.PostProcess));
  82397. BABYLON.FilterPostProcess = FilterPostProcess;
  82398. })(BABYLON || (BABYLON = {}));
  82399. //# sourceMappingURL=babylon.filterPostProcess.js.map
  82400. var BABYLON;
  82401. (function (BABYLON) {
  82402. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  82403. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  82404. __extends(VolumetricLightScatteringPostProcess, _super);
  82405. /**
  82406. * @constructor
  82407. * @param {string} name - The post-process name
  82408. * @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)
  82409. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  82410. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  82411. * @param {number} samples - The post-process quality, default 100
  82412. * @param {number} samplingMode - The post-process filtering mode
  82413. * @param {BABYLON.Engine} engine - The babylon engine
  82414. * @param {boolean} reusable - If the post-process is reusable
  82415. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  82416. */
  82417. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  82418. if (samples === void 0) { samples = 100; }
  82419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82420. 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;
  82421. _this._screenCoordinates = BABYLON.Vector2.Zero();
  82422. /**
  82423. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  82424. */
  82425. _this.customMeshPosition = BABYLON.Vector3.Zero();
  82426. /**
  82427. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  82428. */
  82429. _this.useCustomMeshPosition = false;
  82430. /**
  82431. * If the post-process should inverse the light scattering direction
  82432. */
  82433. _this.invert = true;
  82434. /**
  82435. * Array containing the excluded meshes not rendered in the internal pass
  82436. */
  82437. _this.excludedMeshes = new Array();
  82438. /**
  82439. * Controls the overall intensity of the post-process
  82440. */
  82441. _this.exposure = 0.3;
  82442. /**
  82443. * Dissipates each sample's contribution in range [0, 1]
  82444. */
  82445. _this.decay = 0.96815;
  82446. /**
  82447. * Controls the overall intensity of each sample
  82448. */
  82449. _this.weight = 0.58767;
  82450. /**
  82451. * Controls the density of each sample
  82452. */
  82453. _this.density = 0.926;
  82454. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  82455. engine = scene.getEngine();
  82456. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  82457. // Configure mesh
  82458. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  82459. // Configure
  82460. _this._createPass(scene, ratio.passRatio || ratio);
  82461. _this.onActivate = function (camera) {
  82462. if (!_this.isSupported) {
  82463. _this.dispose(camera);
  82464. }
  82465. _this.onActivate = null;
  82466. };
  82467. _this.onApplyObservable.add(function (effect) {
  82468. _this._updateMeshScreenCoordinates(scene);
  82469. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  82470. effect.setFloat("exposure", _this.exposure);
  82471. effect.setFloat("decay", _this.decay);
  82472. effect.setFloat("weight", _this.weight);
  82473. effect.setFloat("density", _this.density);
  82474. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  82475. });
  82476. return _this;
  82477. }
  82478. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  82479. get: function () {
  82480. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82481. return false;
  82482. },
  82483. set: function (useDiffuseColor) {
  82484. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82485. },
  82486. enumerable: true,
  82487. configurable: true
  82488. });
  82489. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  82490. return "VolumetricLightScatteringPostProcess";
  82491. };
  82492. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  82493. var mesh = subMesh.getMesh();
  82494. // Render this.mesh as default
  82495. if (mesh === this.mesh && mesh.material) {
  82496. return mesh.material.isReady(mesh);
  82497. }
  82498. var defines = [];
  82499. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82500. var material = subMesh.getMaterial();
  82501. // Alpha test
  82502. if (material) {
  82503. if (material.needAlphaTesting()) {
  82504. defines.push("#define ALPHATEST");
  82505. }
  82506. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82507. attribs.push(BABYLON.VertexBuffer.UVKind);
  82508. defines.push("#define UV1");
  82509. }
  82510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82511. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82512. defines.push("#define UV2");
  82513. }
  82514. }
  82515. // Bones
  82516. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82517. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82518. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82519. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82520. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82521. }
  82522. else {
  82523. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82524. }
  82525. // Instances
  82526. if (useInstances) {
  82527. defines.push("#define INSTANCES");
  82528. attribs.push("world0");
  82529. attribs.push("world1");
  82530. attribs.push("world2");
  82531. attribs.push("world3");
  82532. }
  82533. // Get correct effect
  82534. var join = defines.join("\n");
  82535. if (this._cachedDefines !== join) {
  82536. this._cachedDefines = join;
  82537. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  82538. }
  82539. return this._volumetricLightScatteringPass.isReady();
  82540. };
  82541. /**
  82542. * Sets the new light position for light scattering effect
  82543. * @param {BABYLON.Vector3} The new custom light position
  82544. */
  82545. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  82546. this.customMeshPosition = position;
  82547. };
  82548. /**
  82549. * Returns the light position for light scattering effect
  82550. * @return {BABYLON.Vector3} The custom light position
  82551. */
  82552. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  82553. return this.customMeshPosition;
  82554. };
  82555. /**
  82556. * Disposes the internal assets and detaches the post-process from the camera
  82557. */
  82558. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  82559. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  82560. if (rttIndex !== -1) {
  82561. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  82562. }
  82563. this._volumetricLightScatteringRTT.dispose();
  82564. _super.prototype.dispose.call(this, camera);
  82565. };
  82566. /**
  82567. * Returns the render target texture used by the post-process
  82568. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  82569. */
  82570. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  82571. return this._volumetricLightScatteringRTT;
  82572. };
  82573. // Private methods
  82574. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  82575. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  82576. return true;
  82577. }
  82578. return false;
  82579. };
  82580. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  82581. var _this = this;
  82582. var engine = scene.getEngine();
  82583. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82584. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82585. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82586. this._volumetricLightScatteringRTT.renderList = null;
  82587. this._volumetricLightScatteringRTT.renderParticles = false;
  82588. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  82589. var camera = this.getCamera();
  82590. if (camera) {
  82591. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82592. }
  82593. else {
  82594. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82595. }
  82596. // Custom render function for submeshes
  82597. var renderSubMesh = function (subMesh) {
  82598. var mesh = subMesh.getRenderingMesh();
  82599. if (_this._meshExcluded(mesh)) {
  82600. return;
  82601. }
  82602. var material = subMesh.getMaterial();
  82603. if (!material) {
  82604. return;
  82605. }
  82606. var scene = mesh.getScene();
  82607. var engine = scene.getEngine();
  82608. // Culling
  82609. engine.setState(material.backFaceCulling);
  82610. // Managing instances
  82611. var batch = mesh._getInstancesRenderList(subMesh._id);
  82612. if (batch.mustReturn) {
  82613. return;
  82614. }
  82615. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82616. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  82617. var effect = _this._volumetricLightScatteringPass;
  82618. if (mesh === _this.mesh) {
  82619. if (subMesh.effect) {
  82620. effect = subMesh.effect;
  82621. }
  82622. else {
  82623. effect = material.getEffect();
  82624. }
  82625. }
  82626. engine.enableEffect(effect);
  82627. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  82628. if (mesh === _this.mesh) {
  82629. material.bind(mesh.getWorldMatrix(), mesh);
  82630. }
  82631. else {
  82632. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  82633. // Alpha test
  82634. if (material && material.needAlphaTesting()) {
  82635. var alphaTexture = material.getAlphaTestTexture();
  82636. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  82637. if (alphaTexture) {
  82638. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82639. }
  82640. }
  82641. // Bones
  82642. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82643. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82644. }
  82645. }
  82646. // Draw
  82647. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  82648. }
  82649. };
  82650. // Render target texture callbacks
  82651. var savedSceneClearColor;
  82652. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  82653. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  82654. savedSceneClearColor = scene.clearColor;
  82655. scene.clearColor = sceneClearColor;
  82656. });
  82657. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  82658. scene.clearColor = savedSceneClearColor;
  82659. });
  82660. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82661. var engine = scene.getEngine();
  82662. var index;
  82663. if (depthOnlySubMeshes.length) {
  82664. engine.setColorWrite(false);
  82665. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82666. renderSubMesh(depthOnlySubMeshes.data[index]);
  82667. }
  82668. engine.setColorWrite(true);
  82669. }
  82670. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82671. renderSubMesh(opaqueSubMeshes.data[index]);
  82672. }
  82673. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82674. renderSubMesh(alphaTestSubMeshes.data[index]);
  82675. }
  82676. if (transparentSubMeshes.length) {
  82677. // Sort sub meshes
  82678. for (index = 0; index < transparentSubMeshes.length; index++) {
  82679. var submesh = transparentSubMeshes.data[index];
  82680. var boundingInfo = submesh.getBoundingInfo();
  82681. if (boundingInfo && scene.activeCamera) {
  82682. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  82683. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  82684. }
  82685. }
  82686. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82687. sortedArray.sort(function (a, b) {
  82688. // Alpha index first
  82689. if (a._alphaIndex > b._alphaIndex) {
  82690. return 1;
  82691. }
  82692. if (a._alphaIndex < b._alphaIndex) {
  82693. return -1;
  82694. }
  82695. // Then distance to camera
  82696. if (a._distanceToCamera < b._distanceToCamera) {
  82697. return 1;
  82698. }
  82699. if (a._distanceToCamera > b._distanceToCamera) {
  82700. return -1;
  82701. }
  82702. return 0;
  82703. });
  82704. // Render sub meshes
  82705. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82706. for (index = 0; index < sortedArray.length; index++) {
  82707. renderSubMesh(sortedArray[index]);
  82708. }
  82709. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82710. }
  82711. };
  82712. };
  82713. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82714. var transform = scene.getTransformMatrix();
  82715. var meshPosition;
  82716. if (this.useCustomMeshPosition) {
  82717. meshPosition = this.customMeshPosition;
  82718. }
  82719. else if (this.attachedNode) {
  82720. meshPosition = this.attachedNode.position;
  82721. }
  82722. else {
  82723. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82724. }
  82725. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82726. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82727. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82728. if (this.invert)
  82729. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82730. };
  82731. // Static methods
  82732. /**
  82733. * Creates a default mesh for the Volumeric Light Scattering post-process
  82734. * @param {string} The mesh name
  82735. * @param {BABYLON.Scene} The scene where to create the mesh
  82736. * @return {BABYLON.Mesh} the default mesh
  82737. */
  82738. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82739. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82740. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82741. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82742. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82743. mesh.material = material;
  82744. return mesh;
  82745. };
  82746. __decorate([
  82747. BABYLON.serializeAsVector3()
  82748. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82749. __decorate([
  82750. BABYLON.serialize()
  82751. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82752. __decorate([
  82753. BABYLON.serialize()
  82754. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82755. __decorate([
  82756. BABYLON.serializeAsMeshReference()
  82757. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82758. __decorate([
  82759. BABYLON.serialize()
  82760. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82761. __decorate([
  82762. BABYLON.serialize()
  82763. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82764. __decorate([
  82765. BABYLON.serialize()
  82766. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82767. __decorate([
  82768. BABYLON.serialize()
  82769. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82770. __decorate([
  82771. BABYLON.serialize()
  82772. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82773. return VolumetricLightScatteringPostProcess;
  82774. }(BABYLON.PostProcess));
  82775. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82776. })(BABYLON || (BABYLON = {}));
  82777. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82778. //
  82779. // This post-process allows the modification of rendered colors by using
  82780. // a 'look-up table' (LUT). This effect is also called Color Grading.
  82781. //
  82782. // The object needs to be provided an url to a texture containing the color
  82783. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  82784. // Use an image editing software to tweak the LUT to match your needs.
  82785. //
  82786. // For an example of a color LUT, see here:
  82787. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  82788. // For explanations on color grading, see here:
  82789. // http://udn.epicgames.com/Three/ColorGrading.html
  82790. //
  82791. var BABYLON;
  82792. (function (BABYLON) {
  82793. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  82794. __extends(ColorCorrectionPostProcess, _super);
  82795. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  82796. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  82797. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82798. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  82799. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82800. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82801. _this.onApply = function (effect) {
  82802. effect.setTexture("colorTable", _this._colorTableTexture);
  82803. };
  82804. return _this;
  82805. }
  82806. return ColorCorrectionPostProcess;
  82807. }(BABYLON.PostProcess));
  82808. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  82809. })(BABYLON || (BABYLON = {}));
  82810. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  82811. var BABYLON;
  82812. (function (BABYLON) {
  82813. /** Defines operator used for tonemapping */
  82814. var TonemappingOperator;
  82815. (function (TonemappingOperator) {
  82816. /** Hable */
  82817. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  82818. /** Reinhard */
  82819. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  82820. /** HejiDawson */
  82821. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  82822. /** Photographic */
  82823. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  82824. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  82825. ;
  82826. /**
  82827. * Defines a post process to apply tone mapping
  82828. */
  82829. var TonemapPostProcess = /** @class */ (function (_super) {
  82830. __extends(TonemapPostProcess, _super);
  82831. /**
  82832. * Creates a new TonemapPostProcess
  82833. * @param name defines the name of the postprocess
  82834. * @param _operator defines the operator to use
  82835. * @param exposureAdjustment defines the required exposure adjustement
  82836. * @param camera defines the camera to use (can be null)
  82837. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  82838. * @param engine defines the hosting engine (can be ignore if camera is set)
  82839. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  82840. */
  82841. function TonemapPostProcess(name, _operator,
  82842. /** Defines the required exposure adjustement */
  82843. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  82844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82845. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82846. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  82847. _this._operator = _operator;
  82848. _this.exposureAdjustment = exposureAdjustment;
  82849. var defines = "#define ";
  82850. if (_this._operator === TonemappingOperator.Hable)
  82851. defines += "HABLE_TONEMAPPING";
  82852. else if (_this._operator === TonemappingOperator.Reinhard)
  82853. defines += "REINHARD_TONEMAPPING";
  82854. else if (_this._operator === TonemappingOperator.HejiDawson)
  82855. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  82856. else if (_this._operator === TonemappingOperator.Photographic)
  82857. defines += "PHOTOGRAPHIC_TONEMAPPING";
  82858. //sadly a second call to create the effect.
  82859. _this.updateEffect(defines);
  82860. _this.onApply = function (effect) {
  82861. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  82862. };
  82863. return _this;
  82864. }
  82865. return TonemapPostProcess;
  82866. }(BABYLON.PostProcess));
  82867. BABYLON.TonemapPostProcess = TonemapPostProcess;
  82868. })(BABYLON || (BABYLON = {}));
  82869. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  82870. var BABYLON;
  82871. (function (BABYLON) {
  82872. var DisplayPassPostProcess = /** @class */ (function (_super) {
  82873. __extends(DisplayPassPostProcess, _super);
  82874. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  82875. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  82876. }
  82877. return DisplayPassPostProcess;
  82878. }(BABYLON.PostProcess));
  82879. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  82880. })(BABYLON || (BABYLON = {}));
  82881. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  82882. var BABYLON;
  82883. (function (BABYLON) {
  82884. var HighlightsPostProcess = /** @class */ (function (_super) {
  82885. __extends(HighlightsPostProcess, _super);
  82886. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82887. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82888. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82889. }
  82890. return HighlightsPostProcess;
  82891. }(BABYLON.PostProcess));
  82892. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  82893. })(BABYLON || (BABYLON = {}));
  82894. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  82895. var BABYLON;
  82896. (function (BABYLON) {
  82897. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  82898. __extends(ImageProcessingPostProcess, _super);
  82899. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  82900. if (camera === void 0) { camera = null; }
  82901. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82902. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  82903. _this._fromLinearSpace = true;
  82904. /**
  82905. * Defines cache preventing GC.
  82906. */
  82907. _this._defines = {
  82908. IMAGEPROCESSING: false,
  82909. VIGNETTE: false,
  82910. VIGNETTEBLENDMODEMULTIPLY: false,
  82911. VIGNETTEBLENDMODEOPAQUE: false,
  82912. TONEMAPPING: false,
  82913. TONEMAPPING_ACES: false,
  82914. CONTRAST: false,
  82915. COLORCURVES: false,
  82916. COLORGRADING: false,
  82917. COLORGRADING3D: false,
  82918. FROMLINEARSPACE: false,
  82919. SAMPLER3DGREENDEPTH: false,
  82920. SAMPLER3DBGRMAP: false,
  82921. IMAGEPROCESSINGPOSTPROCESS: false,
  82922. EXPOSURE: false,
  82923. };
  82924. // Setup the configuration as forced by the constructor. This would then not force the
  82925. // scene materials output in linear space and let untouched the default forward pass.
  82926. if (imageProcessingConfiguration) {
  82927. imageProcessingConfiguration.applyByPostProcess = true;
  82928. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82929. // This will cause the shader to be compiled
  82930. _this.fromLinearSpace = false;
  82931. }
  82932. // Setup the default processing configuration to the scene.
  82933. else {
  82934. _this._attachImageProcessingConfiguration(null, true);
  82935. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82936. }
  82937. _this.onApply = function (effect) {
  82938. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82939. };
  82940. return _this;
  82941. }
  82942. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82943. /**
  82944. * Gets the image processing configuration used either in this material.
  82945. */
  82946. get: function () {
  82947. return this._imageProcessingConfiguration;
  82948. },
  82949. /**
  82950. * Sets the Default image processing configuration used either in the this material.
  82951. *
  82952. * If sets to null, the scene one is in use.
  82953. */
  82954. set: function (value) {
  82955. this._attachImageProcessingConfiguration(value);
  82956. },
  82957. enumerable: true,
  82958. configurable: true
  82959. });
  82960. /**
  82961. * Attaches a new image processing configuration to the PBR Material.
  82962. * @param configuration
  82963. */
  82964. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82965. var _this = this;
  82966. if (doNotBuild === void 0) { doNotBuild = false; }
  82967. if (configuration === this._imageProcessingConfiguration) {
  82968. return;
  82969. }
  82970. // Detaches observer.
  82971. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82972. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82973. }
  82974. // Pick the scene configuration if needed.
  82975. if (!configuration) {
  82976. var scene = null;
  82977. var engine = this.getEngine();
  82978. var camera = this.getCamera();
  82979. if (camera) {
  82980. scene = camera.getScene();
  82981. }
  82982. else if (engine && engine.scenes) {
  82983. var scenes = engine.scenes;
  82984. scene = scenes[scenes.length - 1];
  82985. }
  82986. else {
  82987. scene = BABYLON.Engine.LastCreatedScene;
  82988. }
  82989. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82990. }
  82991. else {
  82992. this._imageProcessingConfiguration = configuration;
  82993. }
  82994. // Attaches observer.
  82995. if (this._imageProcessingConfiguration) {
  82996. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82997. _this._updateParameters();
  82998. });
  82999. }
  83000. // Ensure the effect will be rebuilt.
  83001. if (!doNotBuild) {
  83002. this._updateParameters();
  83003. }
  83004. };
  83005. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  83006. /**
  83007. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83008. */
  83009. get: function () {
  83010. return this.imageProcessingConfiguration.colorCurves;
  83011. },
  83012. /**
  83013. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83014. */
  83015. set: function (value) {
  83016. this.imageProcessingConfiguration.colorCurves = value;
  83017. },
  83018. enumerable: true,
  83019. configurable: true
  83020. });
  83021. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  83022. /**
  83023. * Gets wether the color curves effect is enabled.
  83024. */
  83025. get: function () {
  83026. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83027. },
  83028. /**
  83029. * Sets wether the color curves effect is enabled.
  83030. */
  83031. set: function (value) {
  83032. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83033. },
  83034. enumerable: true,
  83035. configurable: true
  83036. });
  83037. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  83038. /**
  83039. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83040. */
  83041. get: function () {
  83042. return this.imageProcessingConfiguration.colorGradingTexture;
  83043. },
  83044. /**
  83045. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83046. */
  83047. set: function (value) {
  83048. this.imageProcessingConfiguration.colorGradingTexture = value;
  83049. },
  83050. enumerable: true,
  83051. configurable: true
  83052. });
  83053. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  83054. /**
  83055. * Gets wether the color grading effect is enabled.
  83056. */
  83057. get: function () {
  83058. return this.imageProcessingConfiguration.colorGradingEnabled;
  83059. },
  83060. /**
  83061. * Gets wether the color grading effect is enabled.
  83062. */
  83063. set: function (value) {
  83064. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83065. },
  83066. enumerable: true,
  83067. configurable: true
  83068. });
  83069. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  83070. /**
  83071. * Gets exposure used in the effect.
  83072. */
  83073. get: function () {
  83074. return this.imageProcessingConfiguration.exposure;
  83075. },
  83076. /**
  83077. * Sets exposure used in the effect.
  83078. */
  83079. set: function (value) {
  83080. this.imageProcessingConfiguration.exposure = value;
  83081. },
  83082. enumerable: true,
  83083. configurable: true
  83084. });
  83085. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  83086. /**
  83087. * Gets wether tonemapping is enabled or not.
  83088. */
  83089. get: function () {
  83090. return this._imageProcessingConfiguration.toneMappingEnabled;
  83091. },
  83092. /**
  83093. * Sets wether tonemapping is enabled or not
  83094. */
  83095. set: function (value) {
  83096. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83097. },
  83098. enumerable: true,
  83099. configurable: true
  83100. });
  83101. ;
  83102. ;
  83103. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  83104. /**
  83105. * Gets contrast used in the effect.
  83106. */
  83107. get: function () {
  83108. return this.imageProcessingConfiguration.contrast;
  83109. },
  83110. /**
  83111. * Sets contrast used in the effect.
  83112. */
  83113. set: function (value) {
  83114. this.imageProcessingConfiguration.contrast = value;
  83115. },
  83116. enumerable: true,
  83117. configurable: true
  83118. });
  83119. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  83120. /**
  83121. * Gets Vignette stretch size.
  83122. */
  83123. get: function () {
  83124. return this.imageProcessingConfiguration.vignetteStretch;
  83125. },
  83126. /**
  83127. * Sets Vignette stretch size.
  83128. */
  83129. set: function (value) {
  83130. this.imageProcessingConfiguration.vignetteStretch = value;
  83131. },
  83132. enumerable: true,
  83133. configurable: true
  83134. });
  83135. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  83136. /**
  83137. * Gets Vignette centre X Offset.
  83138. */
  83139. get: function () {
  83140. return this.imageProcessingConfiguration.vignetteCentreX;
  83141. },
  83142. /**
  83143. * Sets Vignette centre X Offset.
  83144. */
  83145. set: function (value) {
  83146. this.imageProcessingConfiguration.vignetteCentreX = value;
  83147. },
  83148. enumerable: true,
  83149. configurable: true
  83150. });
  83151. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  83152. /**
  83153. * Gets Vignette centre Y Offset.
  83154. */
  83155. get: function () {
  83156. return this.imageProcessingConfiguration.vignetteCentreY;
  83157. },
  83158. /**
  83159. * Sets Vignette centre Y Offset.
  83160. */
  83161. set: function (value) {
  83162. this.imageProcessingConfiguration.vignetteCentreY = value;
  83163. },
  83164. enumerable: true,
  83165. configurable: true
  83166. });
  83167. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  83168. /**
  83169. * Gets Vignette weight or intensity of the vignette effect.
  83170. */
  83171. get: function () {
  83172. return this.imageProcessingConfiguration.vignetteWeight;
  83173. },
  83174. /**
  83175. * Sets Vignette weight or intensity of the vignette effect.
  83176. */
  83177. set: function (value) {
  83178. this.imageProcessingConfiguration.vignetteWeight = value;
  83179. },
  83180. enumerable: true,
  83181. configurable: true
  83182. });
  83183. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  83184. /**
  83185. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83186. * if vignetteEnabled is set to true.
  83187. */
  83188. get: function () {
  83189. return this.imageProcessingConfiguration.vignetteColor;
  83190. },
  83191. /**
  83192. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83193. * if vignetteEnabled is set to true.
  83194. */
  83195. set: function (value) {
  83196. this.imageProcessingConfiguration.vignetteColor = value;
  83197. },
  83198. enumerable: true,
  83199. configurable: true
  83200. });
  83201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  83202. /**
  83203. * Gets Camera field of view used by the Vignette effect.
  83204. */
  83205. get: function () {
  83206. return this.imageProcessingConfiguration.vignetteCameraFov;
  83207. },
  83208. /**
  83209. * Sets Camera field of view used by the Vignette effect.
  83210. */
  83211. set: function (value) {
  83212. this.imageProcessingConfiguration.vignetteCameraFov = value;
  83213. },
  83214. enumerable: true,
  83215. configurable: true
  83216. });
  83217. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  83218. /**
  83219. * Gets the vignette blend mode allowing different kind of effect.
  83220. */
  83221. get: function () {
  83222. return this.imageProcessingConfiguration.vignetteBlendMode;
  83223. },
  83224. /**
  83225. * Sets the vignette blend mode allowing different kind of effect.
  83226. */
  83227. set: function (value) {
  83228. this.imageProcessingConfiguration.vignetteBlendMode = value;
  83229. },
  83230. enumerable: true,
  83231. configurable: true
  83232. });
  83233. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  83234. /**
  83235. * Gets wether the vignette effect is enabled.
  83236. */
  83237. get: function () {
  83238. return this.imageProcessingConfiguration.vignetteEnabled;
  83239. },
  83240. /**
  83241. * Sets wether the vignette effect is enabled.
  83242. */
  83243. set: function (value) {
  83244. this.imageProcessingConfiguration.vignetteEnabled = value;
  83245. },
  83246. enumerable: true,
  83247. configurable: true
  83248. });
  83249. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  83250. /**
  83251. * Gets wether the input of the processing is in Gamma or Linear Space.
  83252. */
  83253. get: function () {
  83254. return this._fromLinearSpace;
  83255. },
  83256. /**
  83257. * Sets wether the input of the processing is in Gamma or Linear Space.
  83258. */
  83259. set: function (value) {
  83260. if (this._fromLinearSpace === value) {
  83261. return;
  83262. }
  83263. this._fromLinearSpace = value;
  83264. this._updateParameters();
  83265. },
  83266. enumerable: true,
  83267. configurable: true
  83268. });
  83269. ImageProcessingPostProcess.prototype.getClassName = function () {
  83270. return "ImageProcessingPostProcess";
  83271. };
  83272. ImageProcessingPostProcess.prototype._updateParameters = function () {
  83273. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  83274. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  83275. var defines = "";
  83276. for (var define in this._defines) {
  83277. if (this._defines[define]) {
  83278. defines += "#define " + define + ";\r\n";
  83279. }
  83280. }
  83281. var samplers = ["textureSampler"];
  83282. var uniforms = ["scale"];
  83283. if (BABYLON.ImageProcessingConfiguration) {
  83284. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  83285. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  83286. }
  83287. this.updateEffect(defines, uniforms, samplers);
  83288. };
  83289. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  83290. _super.prototype.dispose.call(this, camera);
  83291. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83292. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83293. }
  83294. if (this._imageProcessingConfiguration) {
  83295. this.imageProcessingConfiguration.applyByPostProcess = false;
  83296. }
  83297. };
  83298. __decorate([
  83299. BABYLON.serialize()
  83300. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  83301. return ImageProcessingPostProcess;
  83302. }(BABYLON.PostProcess));
  83303. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  83304. })(BABYLON || (BABYLON = {}));
  83305. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  83306. var BABYLON;
  83307. (function (BABYLON) {
  83308. /**
  83309. * Class used to store bone information
  83310. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83311. */
  83312. var Bone = /** @class */ (function (_super) {
  83313. __extends(Bone, _super);
  83314. /**
  83315. * Create a new bone
  83316. * @param name defines the bone name
  83317. * @param skeleton defines the parent skeleton
  83318. * @param parentBone defines the parent (can be null if the bone is the root)
  83319. * @param localMatrix defines the local matrix
  83320. * @param restPose defines the rest pose matrix
  83321. * @param baseMatrix defines the base matrix
  83322. * @param index defines index of the bone in the hiearchy
  83323. */
  83324. function Bone(
  83325. /**
  83326. * defines the bone name
  83327. */
  83328. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  83329. if (parentBone === void 0) { parentBone = null; }
  83330. if (localMatrix === void 0) { localMatrix = null; }
  83331. if (restPose === void 0) { restPose = null; }
  83332. if (baseMatrix === void 0) { baseMatrix = null; }
  83333. if (index === void 0) { index = null; }
  83334. var _this = _super.call(this, name, skeleton.getScene()) || this;
  83335. _this.name = name;
  83336. /**
  83337. * Gets the list of child bones
  83338. */
  83339. _this.children = new Array();
  83340. /** Gets the animations associated with this bone */
  83341. _this.animations = new Array();
  83342. /**
  83343. * @hidden Internal only
  83344. * Set this value to map this bone to a different index in the transform matrices
  83345. * Set this value to -1 to exclude the bone from the transform matrices
  83346. */
  83347. _this._index = null;
  83348. _this._absoluteTransform = new BABYLON.Matrix();
  83349. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  83350. _this._scalingDeterminant = 1;
  83351. _this._worldTransform = new BABYLON.Matrix();
  83352. _this._needToDecompose = true;
  83353. _this._needToCompose = false;
  83354. _this._skeleton = skeleton;
  83355. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  83356. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  83357. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  83358. _this._index = index;
  83359. skeleton.bones.push(_this);
  83360. _this.setParent(parentBone, false);
  83361. if (baseMatrix || localMatrix) {
  83362. _this._updateDifferenceMatrix();
  83363. }
  83364. return _this;
  83365. }
  83366. Object.defineProperty(Bone.prototype, "_matrix", {
  83367. /** @hidden */
  83368. get: function () {
  83369. this._compose();
  83370. return this._localMatrix;
  83371. },
  83372. /** @hidden */
  83373. set: function (value) {
  83374. this._localMatrix.copyFrom(value);
  83375. this._needToDecompose = true;
  83376. },
  83377. enumerable: true,
  83378. configurable: true
  83379. });
  83380. // Members
  83381. /**
  83382. * Gets the parent skeleton
  83383. * @returns a skeleton
  83384. */
  83385. Bone.prototype.getSkeleton = function () {
  83386. return this._skeleton;
  83387. };
  83388. /**
  83389. * Gets parent bone
  83390. * @returns a bone or null if the bone is the root of the bone hierarchy
  83391. */
  83392. Bone.prototype.getParent = function () {
  83393. return this._parent;
  83394. };
  83395. /**
  83396. * Sets the parent bone
  83397. * @param parent defines the parent (can be null if the bone is the root)
  83398. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  83399. */
  83400. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  83401. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  83402. if (this._parent === parent) {
  83403. return;
  83404. }
  83405. if (this._parent) {
  83406. var index = this._parent.children.indexOf(this);
  83407. if (index !== -1) {
  83408. this._parent.children.splice(index, 1);
  83409. }
  83410. }
  83411. this._parent = parent;
  83412. if (this._parent) {
  83413. this._parent.children.push(this);
  83414. }
  83415. if (updateDifferenceMatrix) {
  83416. this._updateDifferenceMatrix();
  83417. }
  83418. this.markAsDirty();
  83419. };
  83420. /**
  83421. * Gets the local matrix
  83422. * @returns a matrix
  83423. */
  83424. Bone.prototype.getLocalMatrix = function () {
  83425. this._compose();
  83426. return this._localMatrix;
  83427. };
  83428. /**
  83429. * Gets the base matrix (initial matrix which remains unchanged)
  83430. * @returns a matrix
  83431. */
  83432. Bone.prototype.getBaseMatrix = function () {
  83433. return this._baseMatrix;
  83434. };
  83435. /**
  83436. * Gets the rest pose matrix
  83437. * @returns a matrix
  83438. */
  83439. Bone.prototype.getRestPose = function () {
  83440. return this._restPose;
  83441. };
  83442. /**
  83443. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  83444. */
  83445. Bone.prototype.getWorldMatrix = function () {
  83446. return this._worldTransform;
  83447. };
  83448. /**
  83449. * Sets the local matrix to rest pose matrix
  83450. */
  83451. Bone.prototype.returnToRest = function () {
  83452. this.updateMatrix(this._restPose.clone());
  83453. };
  83454. /**
  83455. * Gets the inverse of the absolute transform matrix.
  83456. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  83457. * @returns a matrix
  83458. */
  83459. Bone.prototype.getInvertedAbsoluteTransform = function () {
  83460. return this._invertedAbsoluteTransform;
  83461. };
  83462. /**
  83463. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  83464. * @returns a matrix
  83465. */
  83466. Bone.prototype.getAbsoluteTransform = function () {
  83467. return this._absoluteTransform;
  83468. };
  83469. Object.defineProperty(Bone.prototype, "position", {
  83470. // Properties (matches AbstractMesh properties)
  83471. /** Gets or sets current position (in local space) */
  83472. get: function () {
  83473. this._decompose();
  83474. return this._localPosition;
  83475. },
  83476. set: function (newPosition) {
  83477. this._decompose();
  83478. this._localPosition.copyFrom(newPosition);
  83479. this._markAsDirtyAndCompose();
  83480. },
  83481. enumerable: true,
  83482. configurable: true
  83483. });
  83484. Object.defineProperty(Bone.prototype, "rotation", {
  83485. /** Gets or sets current rotation (in local space) */
  83486. get: function () {
  83487. return this.getRotation();
  83488. },
  83489. set: function (newRotation) {
  83490. this.setRotation(newRotation);
  83491. },
  83492. enumerable: true,
  83493. configurable: true
  83494. });
  83495. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  83496. /** Gets or sets current rotation quaternion (in local space) */
  83497. get: function () {
  83498. this._decompose();
  83499. return this._localRotation;
  83500. },
  83501. set: function (newRotation) {
  83502. this.setRotationQuaternion(newRotation);
  83503. },
  83504. enumerable: true,
  83505. configurable: true
  83506. });
  83507. Object.defineProperty(Bone.prototype, "scaling", {
  83508. /** Gets or sets current scaling (in local space) */
  83509. get: function () {
  83510. return this.getScale();
  83511. },
  83512. set: function (newScaling) {
  83513. this.setScale(newScaling);
  83514. },
  83515. enumerable: true,
  83516. configurable: true
  83517. });
  83518. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  83519. /**
  83520. * Gets the animation properties override
  83521. */
  83522. get: function () {
  83523. return this._skeleton.animationPropertiesOverride;
  83524. },
  83525. enumerable: true,
  83526. configurable: true
  83527. });
  83528. // Methods
  83529. Bone.prototype._decompose = function () {
  83530. if (!this._needToDecompose) {
  83531. return;
  83532. }
  83533. this._needToDecompose = false;
  83534. if (!this._localScaling) {
  83535. this._localScaling = BABYLON.Vector3.Zero();
  83536. this._localRotation = BABYLON.Quaternion.Zero();
  83537. this._localPosition = BABYLON.Vector3.Zero();
  83538. }
  83539. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  83540. };
  83541. Bone.prototype._compose = function () {
  83542. if (!this._needToCompose) {
  83543. return;
  83544. }
  83545. this._needToCompose = false;
  83546. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  83547. };
  83548. /**
  83549. * Update the base and local matrices
  83550. * @param matrix defines the new base or local matrix
  83551. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  83552. * @param updateLocalMatrix defines if the local matrix should be updated
  83553. */
  83554. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  83555. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  83556. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  83557. this._baseMatrix.copyFrom(matrix);
  83558. if (updateDifferenceMatrix) {
  83559. this._updateDifferenceMatrix();
  83560. }
  83561. if (updateLocalMatrix) {
  83562. this._localMatrix.copyFrom(matrix);
  83563. this._markAsDirtyAndDecompose();
  83564. }
  83565. else {
  83566. this.markAsDirty();
  83567. }
  83568. };
  83569. /** @hidden */
  83570. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  83571. if (updateChildren === void 0) { updateChildren = true; }
  83572. if (!rootMatrix) {
  83573. rootMatrix = this._baseMatrix;
  83574. }
  83575. if (this._parent) {
  83576. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83577. }
  83578. else {
  83579. this._absoluteTransform.copyFrom(rootMatrix);
  83580. }
  83581. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  83582. if (updateChildren) {
  83583. for (var index = 0; index < this.children.length; index++) {
  83584. this.children[index]._updateDifferenceMatrix();
  83585. }
  83586. }
  83587. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  83588. };
  83589. /**
  83590. * Flag the bone as dirty (Forcing it to update everything)
  83591. */
  83592. Bone.prototype.markAsDirty = function () {
  83593. this._currentRenderId++;
  83594. this._childRenderId++;
  83595. this._skeleton._markAsDirty();
  83596. };
  83597. Bone.prototype._markAsDirtyAndCompose = function () {
  83598. this.markAsDirty();
  83599. this._needToCompose = true;
  83600. };
  83601. Bone.prototype._markAsDirtyAndDecompose = function () {
  83602. this.markAsDirty();
  83603. this._needToDecompose = true;
  83604. };
  83605. /**
  83606. * Copy an animation range from another bone
  83607. * @param source defines the source bone
  83608. * @param rangeName defines the range name to copy
  83609. * @param frameOffset defines the frame offset
  83610. * @param rescaleAsRequired defines if rescaling must be applied if required
  83611. * @param skelDimensionsRatio defines the scaling ratio
  83612. * @returns true if operation was successful
  83613. */
  83614. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  83615. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83616. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  83617. // all animation may be coming from a library skeleton, so may need to create animation
  83618. if (this.animations.length === 0) {
  83619. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  83620. this.animations[0].setKeys([]);
  83621. }
  83622. // get animation info / verify there is such a range from the source bone
  83623. var sourceRange = source.animations[0].getRange(rangeName);
  83624. if (!sourceRange) {
  83625. return false;
  83626. }
  83627. var from = sourceRange.from;
  83628. var to = sourceRange.to;
  83629. var sourceKeys = source.animations[0].getKeys();
  83630. // rescaling prep
  83631. var sourceBoneLength = source.length;
  83632. var sourceParent = source.getParent();
  83633. var parent = this.getParent();
  83634. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  83635. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  83636. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  83637. var destKeys = this.animations[0].getKeys();
  83638. // loop vars declaration
  83639. var orig;
  83640. var origTranslation;
  83641. var mat;
  83642. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  83643. orig = sourceKeys[key];
  83644. if (orig.frame >= from && orig.frame <= to) {
  83645. if (rescaleAsRequired) {
  83646. mat = orig.value.clone();
  83647. // scale based on parent ratio, when bone has parent
  83648. if (parentScalingReqd) {
  83649. origTranslation = mat.getTranslation();
  83650. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  83651. // scale based on skeleton dimension ratio when root bone, and value is passed
  83652. }
  83653. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  83654. origTranslation = mat.getTranslation();
  83655. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  83656. // use original when root bone, and no data for skelDimensionsRatio
  83657. }
  83658. else {
  83659. mat = orig.value;
  83660. }
  83661. }
  83662. else {
  83663. mat = orig.value;
  83664. }
  83665. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  83666. }
  83667. }
  83668. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  83669. return true;
  83670. };
  83671. /**
  83672. * Translate the bone in local or world space
  83673. * @param vec The amount to translate the bone
  83674. * @param space The space that the translation is in
  83675. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83676. */
  83677. Bone.prototype.translate = function (vec, space, mesh) {
  83678. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83679. var lm = this.getLocalMatrix();
  83680. if (space == BABYLON.Space.LOCAL) {
  83681. lm.m[12] += vec.x;
  83682. lm.m[13] += vec.y;
  83683. lm.m[14] += vec.z;
  83684. }
  83685. else {
  83686. var wm = null;
  83687. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83688. if (mesh) {
  83689. wm = mesh.getWorldMatrix();
  83690. }
  83691. this._skeleton.computeAbsoluteTransforms();
  83692. var tmat = Bone._tmpMats[0];
  83693. var tvec = Bone._tmpVecs[0];
  83694. if (this._parent) {
  83695. if (mesh && wm) {
  83696. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83697. tmat.multiplyToRef(wm, tmat);
  83698. }
  83699. else {
  83700. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83701. }
  83702. }
  83703. tmat.m[12] = 0;
  83704. tmat.m[13] = 0;
  83705. tmat.m[14] = 0;
  83706. tmat.invert();
  83707. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83708. lm.m[12] += tvec.x;
  83709. lm.m[13] += tvec.y;
  83710. lm.m[14] += tvec.z;
  83711. }
  83712. this._markAsDirtyAndDecompose();
  83713. };
  83714. /**
  83715. * Set the postion of the bone in local or world space
  83716. * @param position The position to set the bone
  83717. * @param space The space that the position is in
  83718. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83719. */
  83720. Bone.prototype.setPosition = function (position, space, mesh) {
  83721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83722. var lm = this.getLocalMatrix();
  83723. if (space == BABYLON.Space.LOCAL) {
  83724. lm.m[12] = position.x;
  83725. lm.m[13] = position.y;
  83726. lm.m[14] = position.z;
  83727. }
  83728. else {
  83729. var wm = null;
  83730. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83731. if (mesh) {
  83732. wm = mesh.getWorldMatrix();
  83733. }
  83734. this._skeleton.computeAbsoluteTransforms();
  83735. var tmat = Bone._tmpMats[0];
  83736. var vec = Bone._tmpVecs[0];
  83737. if (this._parent) {
  83738. if (mesh && wm) {
  83739. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83740. tmat.multiplyToRef(wm, tmat);
  83741. }
  83742. else {
  83743. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83744. }
  83745. }
  83746. tmat.invert();
  83747. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83748. lm.m[12] = vec.x;
  83749. lm.m[13] = vec.y;
  83750. lm.m[14] = vec.z;
  83751. }
  83752. this._markAsDirtyAndDecompose();
  83753. };
  83754. /**
  83755. * Set the absolute position of the bone (world space)
  83756. * @param position The position to set the bone
  83757. * @param mesh The mesh that this bone is attached to
  83758. */
  83759. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83760. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83761. };
  83762. /**
  83763. * Scale the bone on the x, y and z axes (in local space)
  83764. * @param x The amount to scale the bone on the x axis
  83765. * @param y The amount to scale the bone on the y axis
  83766. * @param z The amount to scale the bone on the z axis
  83767. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83768. */
  83769. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83770. if (scaleChildren === void 0) { scaleChildren = false; }
  83771. var locMat = this.getLocalMatrix();
  83772. // Apply new scaling on top of current local matrix
  83773. var scaleMat = Bone._tmpMats[0];
  83774. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83775. scaleMat.multiplyToRef(locMat, locMat);
  83776. // Invert scaling matrix and apply the inverse to all children
  83777. scaleMat.invert();
  83778. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83779. var child = _a[_i];
  83780. var cm = child.getLocalMatrix();
  83781. cm.multiplyToRef(scaleMat, cm);
  83782. cm.m[12] *= x;
  83783. cm.m[13] *= y;
  83784. cm.m[14] *= z;
  83785. child._markAsDirtyAndDecompose();
  83786. }
  83787. this._markAsDirtyAndDecompose();
  83788. if (scaleChildren) {
  83789. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  83790. var child = _c[_b];
  83791. child.scale(x, y, z, scaleChildren);
  83792. }
  83793. }
  83794. };
  83795. /**
  83796. * Set the bone scaling in local space
  83797. * @param scale defines the scaling vector
  83798. */
  83799. Bone.prototype.setScale = function (scale) {
  83800. this._decompose();
  83801. this._localScaling.copyFrom(scale);
  83802. this._markAsDirtyAndCompose();
  83803. };
  83804. /**
  83805. * Gets the current scaling in local space
  83806. * @returns the current scaling vector
  83807. */
  83808. Bone.prototype.getScale = function () {
  83809. this._decompose();
  83810. return this._localScaling;
  83811. };
  83812. /**
  83813. * Gets the current scaling in local space and stores it in a target vector
  83814. * @param result defines the target vector
  83815. */
  83816. Bone.prototype.getScaleToRef = function (result) {
  83817. this._decompose();
  83818. result.copyFrom(this._localScaling);
  83819. };
  83820. /**
  83821. * Set the yaw, pitch, and roll of the bone in local or world space
  83822. * @param yaw The rotation of the bone on the y axis
  83823. * @param pitch The rotation of the bone on the x axis
  83824. * @param roll The rotation of the bone on the z axis
  83825. * @param space The space that the axes of rotation are in
  83826. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83827. */
  83828. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  83829. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83830. if (space === BABYLON.Space.LOCAL) {
  83831. var quat = Bone._tmpQuat;
  83832. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  83833. this.setRotationQuaternion(quat, space, mesh);
  83834. return;
  83835. }
  83836. var rotMatInv = Bone._tmpMats[0];
  83837. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83838. return;
  83839. }
  83840. var rotMat = Bone._tmpMats[1];
  83841. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  83842. rotMatInv.multiplyToRef(rotMat, rotMat);
  83843. this._rotateWithMatrix(rotMat, space, mesh);
  83844. };
  83845. /**
  83846. * Add a rotation to the bone on an axis in local or world space
  83847. * @param axis The axis to rotate the bone on
  83848. * @param amount The amount to rotate the bone
  83849. * @param space The space that the axis is in
  83850. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83851. */
  83852. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  83853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83854. var rmat = Bone._tmpMats[0];
  83855. rmat.m[12] = 0;
  83856. rmat.m[13] = 0;
  83857. rmat.m[14] = 0;
  83858. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  83859. this._rotateWithMatrix(rmat, space, mesh);
  83860. };
  83861. /**
  83862. * Set the rotation of the bone to a particular axis angle in local or world space
  83863. * @param axis The axis to rotate the bone on
  83864. * @param angle The angle that the bone should be rotated to
  83865. * @param space The space that the axis is in
  83866. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83867. */
  83868. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  83869. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83870. if (space === BABYLON.Space.LOCAL) {
  83871. var quat = Bone._tmpQuat;
  83872. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  83873. this.setRotationQuaternion(quat, space, mesh);
  83874. return;
  83875. }
  83876. var rotMatInv = Bone._tmpMats[0];
  83877. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83878. return;
  83879. }
  83880. var rotMat = Bone._tmpMats[1];
  83881. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  83882. rotMatInv.multiplyToRef(rotMat, rotMat);
  83883. this._rotateWithMatrix(rotMat, space, mesh);
  83884. };
  83885. /**
  83886. * Set the euler rotation of the bone in local of world space
  83887. * @param rotation The euler rotation that the bone should be set to
  83888. * @param space The space that the rotation is in
  83889. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83890. */
  83891. Bone.prototype.setRotation = function (rotation, space, mesh) {
  83892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83893. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  83894. };
  83895. /**
  83896. * Set the quaternion rotation of the bone in local of world space
  83897. * @param quat The quaternion rotation that the bone should be set to
  83898. * @param space The space that the rotation is in
  83899. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83900. */
  83901. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  83902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83903. if (space === BABYLON.Space.LOCAL) {
  83904. this._decompose();
  83905. this._localRotation.copyFrom(quat);
  83906. this._markAsDirtyAndCompose();
  83907. return;
  83908. }
  83909. var rotMatInv = Bone._tmpMats[0];
  83910. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83911. return;
  83912. }
  83913. var rotMat = Bone._tmpMats[1];
  83914. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83915. rotMatInv.multiplyToRef(rotMat, rotMat);
  83916. this._rotateWithMatrix(rotMat, space, mesh);
  83917. };
  83918. /**
  83919. * Set the rotation matrix of the bone in local of world space
  83920. * @param rotMat The rotation matrix that the bone should be set to
  83921. * @param space The space that the rotation is in
  83922. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83923. */
  83924. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83925. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83926. if (space === BABYLON.Space.LOCAL) {
  83927. var quat = Bone._tmpQuat;
  83928. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83929. this.setRotationQuaternion(quat, space, mesh);
  83930. return;
  83931. }
  83932. var rotMatInv = Bone._tmpMats[0];
  83933. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83934. return;
  83935. }
  83936. var rotMat2 = Bone._tmpMats[1];
  83937. rotMat2.copyFrom(rotMat);
  83938. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83939. this._rotateWithMatrix(rotMat2, space, mesh);
  83940. };
  83941. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83942. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83943. var lmat = this.getLocalMatrix();
  83944. var lx = lmat.m[12];
  83945. var ly = lmat.m[13];
  83946. var lz = lmat.m[14];
  83947. var parent = this.getParent();
  83948. var parentScale = Bone._tmpMats[3];
  83949. var parentScaleInv = Bone._tmpMats[4];
  83950. if (parent && space == BABYLON.Space.WORLD) {
  83951. if (mesh) {
  83952. parentScale.copyFrom(mesh.getWorldMatrix());
  83953. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83954. }
  83955. else {
  83956. parentScale.copyFrom(parent.getAbsoluteTransform());
  83957. }
  83958. parentScaleInv.copyFrom(parentScale);
  83959. parentScaleInv.invert();
  83960. lmat.multiplyToRef(parentScale, lmat);
  83961. lmat.multiplyToRef(rmat, lmat);
  83962. lmat.multiplyToRef(parentScaleInv, lmat);
  83963. }
  83964. else {
  83965. if (space == BABYLON.Space.WORLD && mesh) {
  83966. parentScale.copyFrom(mesh.getWorldMatrix());
  83967. parentScaleInv.copyFrom(parentScale);
  83968. parentScaleInv.invert();
  83969. lmat.multiplyToRef(parentScale, lmat);
  83970. lmat.multiplyToRef(rmat, lmat);
  83971. lmat.multiplyToRef(parentScaleInv, lmat);
  83972. }
  83973. else {
  83974. lmat.multiplyToRef(rmat, lmat);
  83975. }
  83976. }
  83977. lmat.m[12] = lx;
  83978. lmat.m[13] = ly;
  83979. lmat.m[14] = lz;
  83980. this.computeAbsoluteTransforms();
  83981. this._markAsDirtyAndDecompose();
  83982. };
  83983. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83984. var scaleMatrix = Bone._tmpMats[2];
  83985. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83986. if (mesh) {
  83987. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83988. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83989. }
  83990. rotMatInv.invert();
  83991. if (isNaN(rotMatInv.m[0])) {
  83992. // Matrix failed to invert.
  83993. // This can happen if scale is zero for example.
  83994. return false;
  83995. }
  83996. scaleMatrix.m[0] *= this._scalingDeterminant;
  83997. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83998. return true;
  83999. };
  84000. /**
  84001. * Get the position of the bone in local or world space
  84002. * @param space The space that the returned position is in
  84003. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84004. * @returns The position of the bone
  84005. */
  84006. Bone.prototype.getPosition = function (space, mesh) {
  84007. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84008. if (mesh === void 0) { mesh = null; }
  84009. var pos = BABYLON.Vector3.Zero();
  84010. this.getPositionToRef(space, mesh, pos);
  84011. return pos;
  84012. };
  84013. /**
  84014. * Copy the position of the bone to a vector3 in local or world space
  84015. * @param space The space that the returned position is in
  84016. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84017. * @param result The vector3 to copy the position to
  84018. */
  84019. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  84020. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84021. if (space == BABYLON.Space.LOCAL) {
  84022. var lm = this.getLocalMatrix();
  84023. result.x = lm.m[12];
  84024. result.y = lm.m[13];
  84025. result.z = lm.m[14];
  84026. }
  84027. else {
  84028. var wm = null;
  84029. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84030. if (mesh) {
  84031. wm = mesh.getWorldMatrix();
  84032. }
  84033. this._skeleton.computeAbsoluteTransforms();
  84034. var tmat = Bone._tmpMats[0];
  84035. if (mesh && wm) {
  84036. tmat.copyFrom(this.getAbsoluteTransform());
  84037. tmat.multiplyToRef(wm, tmat);
  84038. }
  84039. else {
  84040. tmat = this.getAbsoluteTransform();
  84041. }
  84042. result.x = tmat.m[12];
  84043. result.y = tmat.m[13];
  84044. result.z = tmat.m[14];
  84045. }
  84046. };
  84047. /**
  84048. * Get the absolute position of the bone (world space)
  84049. * @param mesh The mesh that this bone is attached to
  84050. * @returns The absolute position of the bone
  84051. */
  84052. Bone.prototype.getAbsolutePosition = function (mesh) {
  84053. if (mesh === void 0) { mesh = null; }
  84054. var pos = BABYLON.Vector3.Zero();
  84055. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  84056. return pos;
  84057. };
  84058. /**
  84059. * Copy the absolute position of the bone (world space) to the result param
  84060. * @param mesh The mesh that this bone is attached to
  84061. * @param result The vector3 to copy the absolute position to
  84062. */
  84063. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  84064. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  84065. };
  84066. /**
  84067. * Compute the absolute transforms of this bone and its children
  84068. */
  84069. Bone.prototype.computeAbsoluteTransforms = function () {
  84070. this._compose();
  84071. if (this._parent) {
  84072. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84073. }
  84074. else {
  84075. this._absoluteTransform.copyFrom(this._localMatrix);
  84076. var poseMatrix = this._skeleton.getPoseMatrix();
  84077. if (poseMatrix) {
  84078. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  84079. }
  84080. }
  84081. var children = this.children;
  84082. var len = children.length;
  84083. for (var i = 0; i < len; i++) {
  84084. children[i].computeAbsoluteTransforms();
  84085. }
  84086. };
  84087. /**
  84088. * Get the world direction from an axis that is in the local space of the bone
  84089. * @param localAxis The local direction that is used to compute the world direction
  84090. * @param mesh The mesh that this bone is attached to
  84091. * @returns The world direction
  84092. */
  84093. Bone.prototype.getDirection = function (localAxis, mesh) {
  84094. if (mesh === void 0) { mesh = null; }
  84095. var result = BABYLON.Vector3.Zero();
  84096. this.getDirectionToRef(localAxis, mesh, result);
  84097. return result;
  84098. };
  84099. /**
  84100. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  84101. * @param localAxis The local direction that is used to compute the world direction
  84102. * @param mesh The mesh that this bone is attached to
  84103. * @param result The vector3 that the world direction will be copied to
  84104. */
  84105. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  84106. if (mesh === void 0) { mesh = null; }
  84107. var wm = null;
  84108. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84109. if (mesh) {
  84110. wm = mesh.getWorldMatrix();
  84111. }
  84112. this._skeleton.computeAbsoluteTransforms();
  84113. var mat = Bone._tmpMats[0];
  84114. mat.copyFrom(this.getAbsoluteTransform());
  84115. if (mesh && wm) {
  84116. mat.multiplyToRef(wm, mat);
  84117. }
  84118. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  84119. result.normalize();
  84120. };
  84121. /**
  84122. * Get the euler rotation of the bone in local or world space
  84123. * @param space The space that the rotation should be in
  84124. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84125. * @returns The euler rotation
  84126. */
  84127. Bone.prototype.getRotation = function (space, mesh) {
  84128. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84129. if (mesh === void 0) { mesh = null; }
  84130. var result = BABYLON.Vector3.Zero();
  84131. this.getRotationToRef(space, mesh, result);
  84132. return result;
  84133. };
  84134. /**
  84135. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  84136. * @param space The space that the rotation should be in
  84137. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84138. * @param result The vector3 that the rotation should be copied to
  84139. */
  84140. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  84141. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84142. if (mesh === void 0) { mesh = null; }
  84143. var quat = Bone._tmpQuat;
  84144. this.getRotationQuaternionToRef(space, mesh, quat);
  84145. quat.toEulerAnglesToRef(result);
  84146. };
  84147. /**
  84148. * Get the quaternion rotation of the bone in either local or world space
  84149. * @param space The space that the rotation should be in
  84150. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84151. * @returns The quaternion rotation
  84152. */
  84153. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  84154. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84155. if (mesh === void 0) { mesh = null; }
  84156. var result = BABYLON.Quaternion.Identity();
  84157. this.getRotationQuaternionToRef(space, mesh, result);
  84158. return result;
  84159. };
  84160. /**
  84161. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  84162. * @param space The space that the rotation should be in
  84163. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84164. * @param result The quaternion that the rotation should be copied to
  84165. */
  84166. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  84167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84168. if (mesh === void 0) { mesh = null; }
  84169. if (space == BABYLON.Space.LOCAL) {
  84170. this._decompose();
  84171. result.copyFrom(this._localRotation);
  84172. }
  84173. else {
  84174. var mat = Bone._tmpMats[0];
  84175. var amat = this.getAbsoluteTransform();
  84176. if (mesh) {
  84177. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84178. }
  84179. else {
  84180. mat.copyFrom(amat);
  84181. }
  84182. mat.m[0] *= this._scalingDeterminant;
  84183. mat.m[1] *= this._scalingDeterminant;
  84184. mat.m[2] *= this._scalingDeterminant;
  84185. mat.decompose(undefined, result, undefined);
  84186. }
  84187. };
  84188. /**
  84189. * Get the rotation matrix of the bone in local or world space
  84190. * @param space The space that the rotation should be in
  84191. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84192. * @returns The rotation matrix
  84193. */
  84194. Bone.prototype.getRotationMatrix = function (space, mesh) {
  84195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84196. var result = BABYLON.Matrix.Identity();
  84197. this.getRotationMatrixToRef(space, mesh, result);
  84198. return result;
  84199. };
  84200. /**
  84201. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  84202. * @param space The space that the rotation should be in
  84203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84204. * @param result The quaternion that the rotation should be copied to
  84205. */
  84206. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  84207. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84208. if (space == BABYLON.Space.LOCAL) {
  84209. this.getLocalMatrix().getRotationMatrixToRef(result);
  84210. }
  84211. else {
  84212. var mat = Bone._tmpMats[0];
  84213. var amat = this.getAbsoluteTransform();
  84214. if (mesh) {
  84215. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84216. }
  84217. else {
  84218. mat.copyFrom(amat);
  84219. }
  84220. mat.m[0] *= this._scalingDeterminant;
  84221. mat.m[1] *= this._scalingDeterminant;
  84222. mat.m[2] *= this._scalingDeterminant;
  84223. mat.getRotationMatrixToRef(result);
  84224. }
  84225. };
  84226. /**
  84227. * Get the world position of a point that is in the local space of the bone
  84228. * @param position The local position
  84229. * @param mesh The mesh that this bone is attached to
  84230. * @returns The world position
  84231. */
  84232. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  84233. if (mesh === void 0) { mesh = null; }
  84234. var result = BABYLON.Vector3.Zero();
  84235. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  84236. return result;
  84237. };
  84238. /**
  84239. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  84240. * @param position The local position
  84241. * @param mesh The mesh that this bone is attached to
  84242. * @param result The vector3 that the world position should be copied to
  84243. */
  84244. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  84245. if (mesh === void 0) { mesh = null; }
  84246. var wm = null;
  84247. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84248. if (mesh) {
  84249. wm = mesh.getWorldMatrix();
  84250. }
  84251. this._skeleton.computeAbsoluteTransforms();
  84252. var tmat = Bone._tmpMats[0];
  84253. if (mesh && wm) {
  84254. tmat.copyFrom(this.getAbsoluteTransform());
  84255. tmat.multiplyToRef(wm, tmat);
  84256. }
  84257. else {
  84258. tmat = this.getAbsoluteTransform();
  84259. }
  84260. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84261. };
  84262. /**
  84263. * Get the local position of a point that is in world space
  84264. * @param position The world position
  84265. * @param mesh The mesh that this bone is attached to
  84266. * @returns The local position
  84267. */
  84268. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  84269. if (mesh === void 0) { mesh = null; }
  84270. var result = BABYLON.Vector3.Zero();
  84271. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  84272. return result;
  84273. };
  84274. /**
  84275. * Get the local position of a point that is in world space and copy it to the result param
  84276. * @param position The world position
  84277. * @param mesh The mesh that this bone is attached to
  84278. * @param result The vector3 that the local position should be copied to
  84279. */
  84280. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  84281. if (mesh === void 0) { mesh = null; }
  84282. var wm = null;
  84283. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84284. if (mesh) {
  84285. wm = mesh.getWorldMatrix();
  84286. }
  84287. this._skeleton.computeAbsoluteTransforms();
  84288. var tmat = Bone._tmpMats[0];
  84289. tmat.copyFrom(this.getAbsoluteTransform());
  84290. if (mesh && wm) {
  84291. tmat.multiplyToRef(wm, tmat);
  84292. }
  84293. tmat.invert();
  84294. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84295. };
  84296. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84297. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  84298. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84299. return Bone;
  84300. }(BABYLON.Node));
  84301. BABYLON.Bone = Bone;
  84302. })(BABYLON || (BABYLON = {}));
  84303. //# sourceMappingURL=babylon.bone.js.map
  84304. var BABYLON;
  84305. (function (BABYLON) {
  84306. /**
  84307. * Class used to apply inverse kinematics to bones
  84308. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  84309. */
  84310. var BoneIKController = /** @class */ (function () {
  84311. /**
  84312. * Creates a new BoneIKController
  84313. * @param mesh defines the mesh to control
  84314. * @param bone defines the bone to control
  84315. * @param options defines options to set up the controller
  84316. */
  84317. function BoneIKController(mesh, bone, options) {
  84318. /**
  84319. * Gets or sets the target position
  84320. */
  84321. this.targetPosition = BABYLON.Vector3.Zero();
  84322. /**
  84323. * Gets or sets the pole target position
  84324. */
  84325. this.poleTargetPosition = BABYLON.Vector3.Zero();
  84326. /**
  84327. * Gets or sets the pole target local offset
  84328. */
  84329. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  84330. /**
  84331. * Gets or sets the pole angle
  84332. */
  84333. this.poleAngle = 0;
  84334. /**
  84335. * 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)
  84336. */
  84337. this.slerpAmount = 1;
  84338. this._bone1Quat = BABYLON.Quaternion.Identity();
  84339. this._bone1Mat = BABYLON.Matrix.Identity();
  84340. this._bone2Ang = Math.PI;
  84341. this._maxAngle = Math.PI;
  84342. this._rightHandedSystem = false;
  84343. this._bendAxis = BABYLON.Vector3.Right();
  84344. this._slerping = false;
  84345. this._adjustRoll = 0;
  84346. this._bone2 = bone;
  84347. this._bone1 = bone.getParent();
  84348. if (!this._bone1) {
  84349. return;
  84350. }
  84351. this.mesh = mesh;
  84352. var bonePos = bone.getPosition();
  84353. if (bone.getAbsoluteTransform().determinant() > 0) {
  84354. this._rightHandedSystem = true;
  84355. this._bendAxis.x = 0;
  84356. this._bendAxis.y = 0;
  84357. this._bendAxis.z = -1;
  84358. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  84359. this._adjustRoll = Math.PI * .5;
  84360. this._bendAxis.z = 1;
  84361. }
  84362. }
  84363. if (this._bone1.length) {
  84364. var boneScale1 = this._bone1.getScale();
  84365. var boneScale2 = this._bone2.getScale();
  84366. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  84367. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  84368. }
  84369. else if (this._bone1.children[0]) {
  84370. mesh.computeWorldMatrix(true);
  84371. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  84372. var pos2 = this._bone2.getAbsolutePosition(mesh);
  84373. var pos3 = this._bone1.getAbsolutePosition(mesh);
  84374. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  84375. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  84376. }
  84377. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  84378. this.maxAngle = Math.PI;
  84379. if (options) {
  84380. if (options.targetMesh) {
  84381. this.targetMesh = options.targetMesh;
  84382. this.targetMesh.computeWorldMatrix(true);
  84383. }
  84384. if (options.poleTargetMesh) {
  84385. this.poleTargetMesh = options.poleTargetMesh;
  84386. this.poleTargetMesh.computeWorldMatrix(true);
  84387. }
  84388. else if (options.poleTargetBone) {
  84389. this.poleTargetBone = options.poleTargetBone;
  84390. }
  84391. else if (this._bone1.getParent()) {
  84392. this.poleTargetBone = this._bone1.getParent();
  84393. }
  84394. if (options.poleTargetLocalOffset) {
  84395. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  84396. }
  84397. if (options.poleAngle) {
  84398. this.poleAngle = options.poleAngle;
  84399. }
  84400. if (options.bendAxis) {
  84401. this._bendAxis.copyFrom(options.bendAxis);
  84402. }
  84403. if (options.maxAngle) {
  84404. this.maxAngle = options.maxAngle;
  84405. }
  84406. if (options.slerpAmount) {
  84407. this.slerpAmount = options.slerpAmount;
  84408. }
  84409. }
  84410. }
  84411. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  84412. /**
  84413. * Gets or sets maximum allowed angle
  84414. */
  84415. get: function () {
  84416. return this._maxAngle;
  84417. },
  84418. set: function (value) {
  84419. this._setMaxAngle(value);
  84420. },
  84421. enumerable: true,
  84422. configurable: true
  84423. });
  84424. BoneIKController.prototype._setMaxAngle = function (ang) {
  84425. if (ang < 0) {
  84426. ang = 0;
  84427. }
  84428. if (ang > Math.PI || ang == undefined) {
  84429. ang = Math.PI;
  84430. }
  84431. this._maxAngle = ang;
  84432. var a = this._bone1Length;
  84433. var b = this._bone2Length;
  84434. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  84435. };
  84436. /**
  84437. * Force the controller to update the bones
  84438. */
  84439. BoneIKController.prototype.update = function () {
  84440. var bone1 = this._bone1;
  84441. if (!bone1) {
  84442. return;
  84443. }
  84444. var target = this.targetPosition;
  84445. var poleTarget = this.poleTargetPosition;
  84446. var mat1 = BoneIKController._tmpMats[0];
  84447. var mat2 = BoneIKController._tmpMats[1];
  84448. if (this.targetMesh) {
  84449. target.copyFrom(this.targetMesh.getAbsolutePosition());
  84450. }
  84451. if (this.poleTargetBone) {
  84452. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  84453. }
  84454. else if (this.poleTargetMesh) {
  84455. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  84456. }
  84457. var bonePos = BoneIKController._tmpVecs[0];
  84458. var zaxis = BoneIKController._tmpVecs[1];
  84459. var xaxis = BoneIKController._tmpVecs[2];
  84460. var yaxis = BoneIKController._tmpVecs[3];
  84461. var upAxis = BoneIKController._tmpVecs[4];
  84462. var _tmpQuat = BoneIKController._tmpQuat;
  84463. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  84464. poleTarget.subtractToRef(bonePos, upAxis);
  84465. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  84466. upAxis.y = 1;
  84467. }
  84468. else {
  84469. upAxis.normalize();
  84470. }
  84471. target.subtractToRef(bonePos, yaxis);
  84472. yaxis.normalize();
  84473. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  84474. zaxis.normalize();
  84475. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  84476. xaxis.normalize();
  84477. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  84478. var a = this._bone1Length;
  84479. var b = this._bone2Length;
  84480. var c = BABYLON.Vector3.Distance(bonePos, target);
  84481. if (this._maxReach > 0) {
  84482. c = Math.min(this._maxReach, c);
  84483. }
  84484. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  84485. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  84486. if (acosa > 1) {
  84487. acosa = 1;
  84488. }
  84489. if (acosb > 1) {
  84490. acosb = 1;
  84491. }
  84492. if (acosa < -1) {
  84493. acosa = -1;
  84494. }
  84495. if (acosb < -1) {
  84496. acosb = -1;
  84497. }
  84498. var angA = Math.acos(acosa);
  84499. var angB = Math.acos(acosb);
  84500. var angC = -angA - angB;
  84501. if (this._rightHandedSystem) {
  84502. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  84503. mat2.multiplyToRef(mat1, mat1);
  84504. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  84505. mat2.multiplyToRef(mat1, mat1);
  84506. }
  84507. else {
  84508. var _tmpVec = BoneIKController._tmpVecs[5];
  84509. _tmpVec.copyFrom(this._bendAxis);
  84510. _tmpVec.x *= -1;
  84511. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  84512. mat2.multiplyToRef(mat1, mat1);
  84513. }
  84514. if (this.poleAngle) {
  84515. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  84516. mat1.multiplyToRef(mat2, mat1);
  84517. }
  84518. if (this._bone1) {
  84519. if (this.slerpAmount < 1) {
  84520. if (!this._slerping) {
  84521. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  84522. }
  84523. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  84524. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  84525. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  84526. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  84527. this._slerping = true;
  84528. }
  84529. else {
  84530. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  84531. this._bone1Mat.copyFrom(mat1);
  84532. this._slerping = false;
  84533. }
  84534. }
  84535. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  84536. this._bone2Ang = angC;
  84537. };
  84538. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84539. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  84540. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84541. return BoneIKController;
  84542. }());
  84543. BABYLON.BoneIKController = BoneIKController;
  84544. })(BABYLON || (BABYLON = {}));
  84545. //# sourceMappingURL=babylon.boneIKController.js.map
  84546. var BABYLON;
  84547. (function (BABYLON) {
  84548. /**
  84549. * Class used to make a bone look toward a point in space
  84550. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  84551. */
  84552. var BoneLookController = /** @class */ (function () {
  84553. /**
  84554. * Create a BoneLookController
  84555. * @param mesh the mesh that the bone belongs to
  84556. * @param bone the bone that will be looking to the target
  84557. * @param target the target Vector3 to look at
  84558. * @param settings optional settings:
  84559. * * maxYaw: the maximum angle the bone will yaw to
  84560. * * minYaw: the minimum angle the bone will yaw to
  84561. * * maxPitch: the maximum angle the bone will pitch to
  84562. * * minPitch: the minimum angle the bone will yaw to
  84563. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  84564. * * upAxis: the up axis of the coordinate system
  84565. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  84566. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  84567. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  84568. * * adjustYaw: used to make an adjustment to the yaw of the bone
  84569. * * adjustPitch: used to make an adjustment to the pitch of the bone
  84570. * * adjustRoll: used to make an adjustment to the roll of the bone
  84571. **/
  84572. function BoneLookController(mesh, bone, target, options) {
  84573. /**
  84574. * The up axis of the coordinate system that is used when the bone is rotated
  84575. */
  84576. this.upAxis = BABYLON.Vector3.Up();
  84577. /**
  84578. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  84579. */
  84580. this.upAxisSpace = BABYLON.Space.LOCAL;
  84581. /**
  84582. * Used to make an adjustment to the yaw of the bone
  84583. */
  84584. this.adjustYaw = 0;
  84585. /**
  84586. * Used to make an adjustment to the pitch of the bone
  84587. */
  84588. this.adjustPitch = 0;
  84589. /**
  84590. * Used to make an adjustment to the roll of the bone
  84591. */
  84592. this.adjustRoll = 0;
  84593. /**
  84594. * 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)
  84595. */
  84596. this.slerpAmount = 1;
  84597. this._boneQuat = BABYLON.Quaternion.Identity();
  84598. this._slerping = false;
  84599. this._firstFrameSkipped = false;
  84600. this._fowardAxis = BABYLON.Vector3.Forward();
  84601. this.mesh = mesh;
  84602. this.bone = bone;
  84603. this.target = target;
  84604. if (options) {
  84605. if (options.adjustYaw) {
  84606. this.adjustYaw = options.adjustYaw;
  84607. }
  84608. if (options.adjustPitch) {
  84609. this.adjustPitch = options.adjustPitch;
  84610. }
  84611. if (options.adjustRoll) {
  84612. this.adjustRoll = options.adjustRoll;
  84613. }
  84614. if (options.maxYaw != null) {
  84615. this.maxYaw = options.maxYaw;
  84616. }
  84617. else {
  84618. this.maxYaw = Math.PI;
  84619. }
  84620. if (options.minYaw != null) {
  84621. this.minYaw = options.minYaw;
  84622. }
  84623. else {
  84624. this.minYaw = -Math.PI;
  84625. }
  84626. if (options.maxPitch != null) {
  84627. this.maxPitch = options.maxPitch;
  84628. }
  84629. else {
  84630. this.maxPitch = Math.PI;
  84631. }
  84632. if (options.minPitch != null) {
  84633. this.minPitch = options.minPitch;
  84634. }
  84635. else {
  84636. this.minPitch = -Math.PI;
  84637. }
  84638. if (options.slerpAmount != null) {
  84639. this.slerpAmount = options.slerpAmount;
  84640. }
  84641. if (options.upAxis != null) {
  84642. this.upAxis = options.upAxis;
  84643. }
  84644. if (options.upAxisSpace != null) {
  84645. this.upAxisSpace = options.upAxisSpace;
  84646. }
  84647. if (options.yawAxis != null || options.pitchAxis != null) {
  84648. var newYawAxis = BABYLON.Axis.Y;
  84649. var newPitchAxis = BABYLON.Axis.X;
  84650. if (options.yawAxis != null) {
  84651. newYawAxis = options.yawAxis.clone();
  84652. newYawAxis.normalize();
  84653. }
  84654. if (options.pitchAxis != null) {
  84655. newPitchAxis = options.pitchAxis.clone();
  84656. newPitchAxis.normalize();
  84657. }
  84658. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  84659. this._transformYawPitch = BABYLON.Matrix.Identity();
  84660. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  84661. this._transformYawPitchInv = this._transformYawPitch.clone();
  84662. this._transformYawPitch.invert();
  84663. }
  84664. }
  84665. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  84666. this.upAxisSpace = BABYLON.Space.LOCAL;
  84667. }
  84668. }
  84669. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  84670. /**
  84671. * Gets or sets the minimum yaw angle that the bone can look to
  84672. */
  84673. get: function () {
  84674. return this._minYaw;
  84675. },
  84676. set: function (value) {
  84677. this._minYaw = value;
  84678. this._minYawSin = Math.sin(value);
  84679. this._minYawCos = Math.cos(value);
  84680. if (this._maxYaw != null) {
  84681. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84682. this._yawRange = this._maxYaw - this._minYaw;
  84683. }
  84684. },
  84685. enumerable: true,
  84686. configurable: true
  84687. });
  84688. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84689. /**
  84690. * Gets or sets the maximum yaw angle that the bone can look to
  84691. */
  84692. get: function () {
  84693. return this._maxYaw;
  84694. },
  84695. set: function (value) {
  84696. this._maxYaw = value;
  84697. this._maxYawSin = Math.sin(value);
  84698. this._maxYawCos = Math.cos(value);
  84699. if (this._minYaw != null) {
  84700. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84701. this._yawRange = this._maxYaw - this._minYaw;
  84702. }
  84703. },
  84704. enumerable: true,
  84705. configurable: true
  84706. });
  84707. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84708. /**
  84709. * Gets or sets the minimum pitch angle that the bone can look to
  84710. */
  84711. get: function () {
  84712. return this._minPitch;
  84713. },
  84714. set: function (value) {
  84715. this._minPitch = value;
  84716. this._minPitchTan = Math.tan(value);
  84717. },
  84718. enumerable: true,
  84719. configurable: true
  84720. });
  84721. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84722. /**
  84723. * Gets or sets the maximum pitch angle that the bone can look to
  84724. */
  84725. get: function () {
  84726. return this._maxPitch;
  84727. },
  84728. set: function (value) {
  84729. this._maxPitch = value;
  84730. this._maxPitchTan = Math.tan(value);
  84731. },
  84732. enumerable: true,
  84733. configurable: true
  84734. });
  84735. /**
  84736. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84737. */
  84738. BoneLookController.prototype.update = function () {
  84739. //skip the first frame when slerping so that the mesh rotation is correct
  84740. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84741. this._firstFrameSkipped = true;
  84742. return;
  84743. }
  84744. var bone = this.bone;
  84745. var bonePos = BoneLookController._tmpVecs[0];
  84746. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84747. var target = this.target;
  84748. var _tmpMat1 = BoneLookController._tmpMats[0];
  84749. var _tmpMat2 = BoneLookController._tmpMats[1];
  84750. var mesh = this.mesh;
  84751. var parentBone = bone.getParent();
  84752. var upAxis = BoneLookController._tmpVecs[1];
  84753. upAxis.copyFrom(this.upAxis);
  84754. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84755. if (this._transformYawPitch) {
  84756. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84757. }
  84758. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84759. }
  84760. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84761. mesh.getDirectionToRef(upAxis, upAxis);
  84762. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84763. upAxis.normalize();
  84764. }
  84765. }
  84766. var checkYaw = false;
  84767. var checkPitch = false;
  84768. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84769. checkYaw = true;
  84770. }
  84771. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84772. checkPitch = true;
  84773. }
  84774. if (checkYaw || checkPitch) {
  84775. var spaceMat = BoneLookController._tmpMats[2];
  84776. var spaceMatInv = BoneLookController._tmpMats[3];
  84777. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84778. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84779. }
  84780. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  84781. spaceMat.copyFrom(mesh.getWorldMatrix());
  84782. }
  84783. else {
  84784. var forwardAxis = BoneLookController._tmpVecs[2];
  84785. forwardAxis.copyFrom(this._fowardAxis);
  84786. if (this._transformYawPitch) {
  84787. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  84788. }
  84789. if (parentBone) {
  84790. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  84791. }
  84792. else {
  84793. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  84794. }
  84795. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  84796. rightAxis.normalize();
  84797. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  84798. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  84799. }
  84800. spaceMat.invertToRef(spaceMatInv);
  84801. var xzlen = null;
  84802. if (checkPitch) {
  84803. var localTarget = BoneLookController._tmpVecs[3];
  84804. target.subtractToRef(bonePos, localTarget);
  84805. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84806. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84807. var pitch = Math.atan2(localTarget.y, xzlen);
  84808. var newPitch = pitch;
  84809. if (pitch > this._maxPitch) {
  84810. localTarget.y = this._maxPitchTan * xzlen;
  84811. newPitch = this._maxPitch;
  84812. }
  84813. else if (pitch < this._minPitch) {
  84814. localTarget.y = this._minPitchTan * xzlen;
  84815. newPitch = this._minPitch;
  84816. }
  84817. if (pitch != newPitch) {
  84818. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84819. localTarget.addInPlace(bonePos);
  84820. target = localTarget;
  84821. }
  84822. }
  84823. if (checkYaw) {
  84824. var localTarget = BoneLookController._tmpVecs[4];
  84825. target.subtractToRef(bonePos, localTarget);
  84826. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84827. var yaw = Math.atan2(localTarget.x, localTarget.z);
  84828. var newYaw = yaw;
  84829. if (yaw > this._maxYaw || yaw < this._minYaw) {
  84830. if (xzlen == null) {
  84831. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84832. }
  84833. if (this._yawRange > Math.PI) {
  84834. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  84835. localTarget.z = this._maxYawCos * xzlen;
  84836. localTarget.x = this._maxYawSin * xzlen;
  84837. newYaw = this._maxYaw;
  84838. }
  84839. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  84840. localTarget.z = this._minYawCos * xzlen;
  84841. localTarget.x = this._minYawSin * xzlen;
  84842. newYaw = this._minYaw;
  84843. }
  84844. }
  84845. else {
  84846. if (yaw > this._maxYaw) {
  84847. localTarget.z = this._maxYawCos * xzlen;
  84848. localTarget.x = this._maxYawSin * xzlen;
  84849. newYaw = this._maxYaw;
  84850. }
  84851. else if (yaw < this._minYaw) {
  84852. localTarget.z = this._minYawCos * xzlen;
  84853. localTarget.x = this._minYawSin * xzlen;
  84854. newYaw = this._minYaw;
  84855. }
  84856. }
  84857. }
  84858. if (this._slerping && this._yawRange > Math.PI) {
  84859. //are we going to be crossing into the min/max region?
  84860. var boneFwd = BoneLookController._tmpVecs[8];
  84861. boneFwd.copyFrom(BABYLON.Axis.Z);
  84862. if (this._transformYawPitch) {
  84863. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  84864. }
  84865. var boneRotMat = BoneLookController._tmpMats[4];
  84866. this._boneQuat.toRotationMatrix(boneRotMat);
  84867. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  84868. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  84869. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  84870. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  84871. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  84872. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  84873. if (angBtwTar > angBtwMidYaw) {
  84874. if (xzlen == null) {
  84875. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84876. }
  84877. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  84878. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  84879. if (angBtwMin < angBtwMax) {
  84880. newYaw = boneYaw + Math.PI * .75;
  84881. localTarget.z = Math.cos(newYaw) * xzlen;
  84882. localTarget.x = Math.sin(newYaw) * xzlen;
  84883. }
  84884. else {
  84885. newYaw = boneYaw - Math.PI * .75;
  84886. localTarget.z = Math.cos(newYaw) * xzlen;
  84887. localTarget.x = Math.sin(newYaw) * xzlen;
  84888. }
  84889. }
  84890. }
  84891. if (yaw != newYaw) {
  84892. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84893. localTarget.addInPlace(bonePos);
  84894. target = localTarget;
  84895. }
  84896. }
  84897. }
  84898. var zaxis = BoneLookController._tmpVecs[5];
  84899. var xaxis = BoneLookController._tmpVecs[6];
  84900. var yaxis = BoneLookController._tmpVecs[7];
  84901. var _tmpQuat = BoneLookController._tmpQuat;
  84902. target.subtractToRef(bonePos, zaxis);
  84903. zaxis.normalize();
  84904. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  84905. xaxis.normalize();
  84906. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  84907. yaxis.normalize();
  84908. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  84909. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  84910. return;
  84911. }
  84912. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  84913. return;
  84914. }
  84915. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84916. return;
  84917. }
  84918. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84919. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84920. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84921. }
  84922. if (this.slerpAmount < 1) {
  84923. if (!this._slerping) {
  84924. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84925. }
  84926. if (this._transformYawPitch) {
  84927. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84928. }
  84929. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84930. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84931. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84932. this._slerping = true;
  84933. }
  84934. else {
  84935. if (this._transformYawPitch) {
  84936. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84937. }
  84938. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84939. this._slerping = false;
  84940. }
  84941. };
  84942. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84943. var angDiff = ang2 - ang1;
  84944. angDiff %= Math.PI * 2;
  84945. if (angDiff > Math.PI) {
  84946. angDiff -= Math.PI * 2;
  84947. }
  84948. else if (angDiff < -Math.PI) {
  84949. angDiff += Math.PI * 2;
  84950. }
  84951. return angDiff;
  84952. };
  84953. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84954. ang1 %= (2 * Math.PI);
  84955. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84956. ang2 %= (2 * Math.PI);
  84957. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84958. var ab = 0;
  84959. if (ang1 < ang2) {
  84960. ab = ang2 - ang1;
  84961. }
  84962. else {
  84963. ab = ang1 - ang2;
  84964. }
  84965. if (ab > Math.PI) {
  84966. ab = Math.PI * 2 - ab;
  84967. }
  84968. return ab;
  84969. };
  84970. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84971. ang %= (2 * Math.PI);
  84972. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84973. ang1 %= (2 * Math.PI);
  84974. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84975. ang2 %= (2 * Math.PI);
  84976. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84977. if (ang1 < ang2) {
  84978. if (ang > ang1 && ang < ang2) {
  84979. return true;
  84980. }
  84981. }
  84982. else {
  84983. if (ang > ang2 && ang < ang1) {
  84984. return true;
  84985. }
  84986. }
  84987. return false;
  84988. };
  84989. 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()];
  84990. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84991. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84992. return BoneLookController;
  84993. }());
  84994. BABYLON.BoneLookController = BoneLookController;
  84995. })(BABYLON || (BABYLON = {}));
  84996. //# sourceMappingURL=babylon.boneLookController.js.map
  84997. var BABYLON;
  84998. (function (BABYLON) {
  84999. /**
  85000. * Class used to handle skinning animations
  85001. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85002. */
  85003. var Skeleton = /** @class */ (function () {
  85004. /**
  85005. * Creates a new skeleton
  85006. * @param name defines the skeleton name
  85007. * @param id defines the skeleton Id
  85008. * @param scene defines the hosting scene
  85009. */
  85010. function Skeleton(
  85011. /** defines the skeleton name */
  85012. name,
  85013. /** defines the skeleton Id */
  85014. id, scene) {
  85015. this.name = name;
  85016. this.id = id;
  85017. /**
  85018. * Gets the list of child bones
  85019. */
  85020. this.bones = new Array();
  85021. /**
  85022. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  85023. */
  85024. this.needInitialSkinMatrix = false;
  85025. this._isDirty = true;
  85026. this._meshesWithPoseMatrix = new Array();
  85027. this._identity = BABYLON.Matrix.Identity();
  85028. this._ranges = {};
  85029. this._lastAbsoluteTransformsUpdateId = -1;
  85030. /**
  85031. * Specifies if the skeleton should be serialized
  85032. */
  85033. this.doNotSerialize = false;
  85034. this._animationPropertiesOverride = null;
  85035. // Events
  85036. /**
  85037. * An observable triggered before computing the skeleton's matrices
  85038. */
  85039. this.onBeforeComputeObservable = new BABYLON.Observable();
  85040. this.bones = [];
  85041. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85042. scene.skeletons.push(this);
  85043. //make sure it will recalculate the matrix next time prepare is called.
  85044. this._isDirty = true;
  85045. }
  85046. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  85047. /**
  85048. * Gets or sets the animation properties override
  85049. */
  85050. get: function () {
  85051. if (!this._animationPropertiesOverride) {
  85052. return this._scene.animationPropertiesOverride;
  85053. }
  85054. return this._animationPropertiesOverride;
  85055. },
  85056. set: function (value) {
  85057. this._animationPropertiesOverride = value;
  85058. },
  85059. enumerable: true,
  85060. configurable: true
  85061. });
  85062. // Members
  85063. /**
  85064. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  85065. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  85066. * @returns a Float32Array containing matrices data
  85067. */
  85068. Skeleton.prototype.getTransformMatrices = function (mesh) {
  85069. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  85070. return mesh._bonesTransformMatrices;
  85071. }
  85072. if (!this._transformMatrices) {
  85073. this.prepare();
  85074. }
  85075. return this._transformMatrices;
  85076. };
  85077. /**
  85078. * Gets the current hosting scene
  85079. * @returns a scene object
  85080. */
  85081. Skeleton.prototype.getScene = function () {
  85082. return this._scene;
  85083. };
  85084. // Methods
  85085. /**
  85086. * Gets a string representing the current skeleton data
  85087. * @param fullDetails defines a boolean indicating if we want a verbose version
  85088. * @returns a string representing the current skeleton data
  85089. */
  85090. Skeleton.prototype.toString = function (fullDetails) {
  85091. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  85092. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  85093. if (fullDetails) {
  85094. ret += ", Ranges: {";
  85095. var first = true;
  85096. for (var name_1 in this._ranges) {
  85097. if (first) {
  85098. ret += ", ";
  85099. first = false;
  85100. }
  85101. ret += name_1;
  85102. }
  85103. ret += "}";
  85104. }
  85105. return ret;
  85106. };
  85107. /**
  85108. * Get bone's index searching by name
  85109. * @param name defines bone's name to search for
  85110. * @return the indice of the bone. Returns -1 if not found
  85111. */
  85112. Skeleton.prototype.getBoneIndexByName = function (name) {
  85113. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  85114. if (this.bones[boneIndex].name === name) {
  85115. return boneIndex;
  85116. }
  85117. }
  85118. return -1;
  85119. };
  85120. /**
  85121. * Creater a new animation range
  85122. * @param name defines the name of the range
  85123. * @param from defines the start key
  85124. * @param to defines the end key
  85125. */
  85126. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  85127. // check name not already in use
  85128. if (!this._ranges[name]) {
  85129. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  85130. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85131. if (this.bones[i].animations[0]) {
  85132. this.bones[i].animations[0].createRange(name, from, to);
  85133. }
  85134. }
  85135. }
  85136. };
  85137. /**
  85138. * Delete a specific animation range
  85139. * @param name defines the name of the range
  85140. * @param deleteFrames defines if frames must be removed as well
  85141. */
  85142. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  85143. if (deleteFrames === void 0) { deleteFrames = true; }
  85144. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85145. if (this.bones[i].animations[0]) {
  85146. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  85147. }
  85148. }
  85149. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  85150. };
  85151. /**
  85152. * Gets a specific animation range
  85153. * @param name defines the name of the range to look for
  85154. * @returns the requested animation range or null if not found
  85155. */
  85156. Skeleton.prototype.getAnimationRange = function (name) {
  85157. return this._ranges[name];
  85158. };
  85159. /**
  85160. * Gets the list of all animation ranges defined on this skeleton
  85161. * @returns an array
  85162. */
  85163. Skeleton.prototype.getAnimationRanges = function () {
  85164. var animationRanges = [];
  85165. var name;
  85166. var i = 0;
  85167. for (name in this._ranges) {
  85168. animationRanges[i] = this._ranges[name];
  85169. i++;
  85170. }
  85171. return animationRanges;
  85172. };
  85173. /**
  85174. * Copy animation range from a source skeleton.
  85175. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  85176. * @param source defines the source skeleton
  85177. * @param name defines the name of the range to copy
  85178. * @param rescaleAsRequired defines if rescaling must be applied if required
  85179. * @returns true if operation was successful
  85180. */
  85181. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  85182. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  85183. if (this._ranges[name] || !source.getAnimationRange(name)) {
  85184. return false;
  85185. }
  85186. var ret = true;
  85187. var frameOffset = this._getHighestAnimationFrame() + 1;
  85188. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  85189. var boneDict = {};
  85190. var sourceBones = source.bones;
  85191. var nBones;
  85192. var i;
  85193. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  85194. boneDict[sourceBones[i].name] = sourceBones[i];
  85195. }
  85196. if (this.bones.length !== sourceBones.length) {
  85197. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  85198. ret = false;
  85199. }
  85200. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  85201. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  85202. var boneName = this.bones[i].name;
  85203. var sourceBone = boneDict[boneName];
  85204. if (sourceBone) {
  85205. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  85206. }
  85207. else {
  85208. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  85209. ret = false;
  85210. }
  85211. }
  85212. // do not call createAnimationRange(), since it also is done to bones, which was already done
  85213. var range = source.getAnimationRange(name);
  85214. if (range) {
  85215. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  85216. }
  85217. return ret;
  85218. };
  85219. /**
  85220. * Forces the skeleton to go to rest pose
  85221. */
  85222. Skeleton.prototype.returnToRest = function () {
  85223. for (var index = 0; index < this.bones.length; index++) {
  85224. this.bones[index].returnToRest();
  85225. }
  85226. };
  85227. Skeleton.prototype._getHighestAnimationFrame = function () {
  85228. var ret = 0;
  85229. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85230. if (this.bones[i].animations[0]) {
  85231. var highest = this.bones[i].animations[0].getHighestFrame();
  85232. if (ret < highest) {
  85233. ret = highest;
  85234. }
  85235. }
  85236. }
  85237. return ret;
  85238. };
  85239. /**
  85240. * Begin a specific animation range
  85241. * @param name defines the name of the range to start
  85242. * @param loop defines if looping must be turned on (false by default)
  85243. * @param speedRatio defines the speed ratio to apply (1 by default)
  85244. * @param onAnimationEnd defines a callback which will be called when animation will end
  85245. * @returns a new animatable
  85246. */
  85247. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  85248. var range = this.getAnimationRange(name);
  85249. if (!range) {
  85250. return null;
  85251. }
  85252. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  85253. };
  85254. /** @hidden */
  85255. Skeleton.prototype._markAsDirty = function () {
  85256. this._isDirty = true;
  85257. };
  85258. /** @hidden */
  85259. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  85260. this._meshesWithPoseMatrix.push(mesh);
  85261. };
  85262. /** @hidden */
  85263. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  85264. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  85265. if (index > -1) {
  85266. this._meshesWithPoseMatrix.splice(index, 1);
  85267. }
  85268. };
  85269. /** @hidden */
  85270. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  85271. this.onBeforeComputeObservable.notifyObservers(this);
  85272. for (var index = 0; index < this.bones.length; index++) {
  85273. var bone = this.bones[index];
  85274. var parentBone = bone.getParent();
  85275. if (parentBone) {
  85276. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  85277. }
  85278. else {
  85279. if (initialSkinMatrix) {
  85280. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  85281. }
  85282. else {
  85283. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  85284. }
  85285. }
  85286. if (bone._index !== -1) {
  85287. var mappedIndex = bone._index === null ? index : bone._index;
  85288. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  85289. }
  85290. }
  85291. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  85292. };
  85293. /**
  85294. * Build all resources required to render a skeleton
  85295. */
  85296. Skeleton.prototype.prepare = function () {
  85297. if (!this._isDirty) {
  85298. return;
  85299. }
  85300. if (this.needInitialSkinMatrix) {
  85301. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  85302. var mesh = this._meshesWithPoseMatrix[index];
  85303. var poseMatrix = mesh.getPoseMatrix();
  85304. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  85305. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  85306. }
  85307. if (this._synchronizedWithMesh !== mesh) {
  85308. this._synchronizedWithMesh = mesh;
  85309. // Prepare bones
  85310. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  85311. var bone = this.bones[boneIndex];
  85312. if (!bone.getParent()) {
  85313. var matrix = bone.getBaseMatrix();
  85314. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  85315. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  85316. }
  85317. }
  85318. }
  85319. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  85320. }
  85321. }
  85322. else {
  85323. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  85324. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  85325. }
  85326. this._computeTransformMatrices(this._transformMatrices, null);
  85327. }
  85328. this._isDirty = false;
  85329. this._scene._activeBones.addCount(this.bones.length, false);
  85330. };
  85331. /**
  85332. * Gets the list of animatables currently running for this skeleton
  85333. * @returns an array of animatables
  85334. */
  85335. Skeleton.prototype.getAnimatables = function () {
  85336. if (!this._animatables || this._animatables.length !== this.bones.length) {
  85337. this._animatables = [];
  85338. for (var index = 0; index < this.bones.length; index++) {
  85339. this._animatables.push(this.bones[index]);
  85340. }
  85341. }
  85342. return this._animatables;
  85343. };
  85344. /**
  85345. * Clone the current skeleton
  85346. * @param name defines the name of the new skeleton
  85347. * @param id defines the id of the enw skeleton
  85348. * @returns the new skeleton
  85349. */
  85350. Skeleton.prototype.clone = function (name, id) {
  85351. var result = new Skeleton(name, id || name, this._scene);
  85352. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  85353. for (var index = 0; index < this.bones.length; index++) {
  85354. var source = this.bones[index];
  85355. var parentBone = null;
  85356. var parent_1 = source.getParent();
  85357. if (parent_1) {
  85358. var parentIndex = this.bones.indexOf(parent_1);
  85359. parentBone = result.bones[parentIndex];
  85360. }
  85361. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  85362. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  85363. }
  85364. if (this._ranges) {
  85365. result._ranges = {};
  85366. for (var rangeName in this._ranges) {
  85367. var range = this._ranges[rangeName];
  85368. if (range) {
  85369. result._ranges[rangeName] = range.clone();
  85370. }
  85371. }
  85372. }
  85373. this._isDirty = true;
  85374. return result;
  85375. };
  85376. /**
  85377. * Enable animation blending for this skeleton
  85378. * @param blendingSpeed defines the blending speed to apply
  85379. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  85380. */
  85381. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  85382. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  85383. this.bones.forEach(function (bone) {
  85384. bone.animations.forEach(function (animation) {
  85385. animation.enableBlending = true;
  85386. animation.blendingSpeed = blendingSpeed;
  85387. });
  85388. });
  85389. };
  85390. /**
  85391. * Releases all resources associated with the current skeleton
  85392. */
  85393. Skeleton.prototype.dispose = function () {
  85394. this._meshesWithPoseMatrix = [];
  85395. // Animations
  85396. this.getScene().stopAnimation(this);
  85397. // Remove from scene
  85398. this.getScene().removeSkeleton(this);
  85399. };
  85400. /**
  85401. * Serialize the skeleton in a JSON object
  85402. * @returns a JSON object
  85403. */
  85404. Skeleton.prototype.serialize = function () {
  85405. var serializationObject = {};
  85406. serializationObject.name = this.name;
  85407. serializationObject.id = this.id;
  85408. if (this.dimensionsAtRest) {
  85409. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  85410. }
  85411. serializationObject.bones = [];
  85412. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  85413. for (var index = 0; index < this.bones.length; index++) {
  85414. var bone = this.bones[index];
  85415. var parent_2 = bone.getParent();
  85416. var serializedBone = {
  85417. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  85418. name: bone.name,
  85419. matrix: bone.getBaseMatrix().toArray(),
  85420. rest: bone.getRestPose().toArray()
  85421. };
  85422. serializationObject.bones.push(serializedBone);
  85423. if (bone.length) {
  85424. serializedBone.length = bone.length;
  85425. }
  85426. if (bone.metadata) {
  85427. serializedBone.metadata = bone.metadata;
  85428. }
  85429. if (bone.animations && bone.animations.length > 0) {
  85430. serializedBone.animation = bone.animations[0].serialize();
  85431. }
  85432. serializationObject.ranges = [];
  85433. for (var name in this._ranges) {
  85434. var source = this._ranges[name];
  85435. if (!source) {
  85436. continue;
  85437. }
  85438. var range = {};
  85439. range.name = name;
  85440. range.from = source.from;
  85441. range.to = source.to;
  85442. serializationObject.ranges.push(range);
  85443. }
  85444. }
  85445. return serializationObject;
  85446. };
  85447. /**
  85448. * Creates a new skeleton from serialized data
  85449. * @param parsedSkeleton defines the serialized data
  85450. * @param scene defines the hosting scene
  85451. * @returns a new skeleton
  85452. */
  85453. Skeleton.Parse = function (parsedSkeleton, scene) {
  85454. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  85455. if (parsedSkeleton.dimensionsAtRest) {
  85456. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  85457. }
  85458. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  85459. var index;
  85460. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  85461. var parsedBone = parsedSkeleton.bones[index];
  85462. var parentBone = null;
  85463. if (parsedBone.parentBoneIndex > -1) {
  85464. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  85465. }
  85466. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  85467. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  85468. if (parsedBone.length) {
  85469. bone.length = parsedBone.length;
  85470. }
  85471. if (parsedBone.metadata) {
  85472. bone.metadata = parsedBone.metadata;
  85473. }
  85474. if (parsedBone.animation) {
  85475. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  85476. }
  85477. }
  85478. // placed after bones, so createAnimationRange can cascade down
  85479. if (parsedSkeleton.ranges) {
  85480. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  85481. var data = parsedSkeleton.ranges[index];
  85482. skeleton.createAnimationRange(data.name, data.from, data.to);
  85483. }
  85484. }
  85485. return skeleton;
  85486. };
  85487. /**
  85488. * Compute all node absolute transforms
  85489. * @param forceUpdate defines if computation must be done even if cache is up to date
  85490. */
  85491. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  85492. if (forceUpdate === void 0) { forceUpdate = false; }
  85493. var renderId = this._scene.getRenderId();
  85494. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  85495. this.bones[0].computeAbsoluteTransforms();
  85496. this._lastAbsoluteTransformsUpdateId = renderId;
  85497. }
  85498. };
  85499. /**
  85500. * Gets the root pose matrix
  85501. * @returns a matrix
  85502. */
  85503. Skeleton.prototype.getPoseMatrix = function () {
  85504. var poseMatrix = null;
  85505. if (this._meshesWithPoseMatrix.length > 0) {
  85506. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  85507. }
  85508. return poseMatrix;
  85509. };
  85510. /**
  85511. * Sorts bones per internal index
  85512. */
  85513. Skeleton.prototype.sortBones = function () {
  85514. var bones = new Array();
  85515. var visited = new Array(this.bones.length);
  85516. for (var index = 0; index < this.bones.length; index++) {
  85517. this._sortBones(index, bones, visited);
  85518. }
  85519. this.bones = bones;
  85520. };
  85521. Skeleton.prototype._sortBones = function (index, bones, visited) {
  85522. if (visited[index]) {
  85523. return;
  85524. }
  85525. visited[index] = true;
  85526. var bone = this.bones[index];
  85527. if (bone._index === undefined) {
  85528. bone._index = index;
  85529. }
  85530. var parentBone = bone.getParent();
  85531. if (parentBone) {
  85532. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  85533. }
  85534. bones.push(bone);
  85535. };
  85536. return Skeleton;
  85537. }());
  85538. BABYLON.Skeleton = Skeleton;
  85539. })(BABYLON || (BABYLON = {}));
  85540. //# sourceMappingURL=babylon.skeleton.js.map
  85541. var BABYLON;
  85542. (function (BABYLON) {
  85543. ;
  85544. /**
  85545. * This groups tools to convert HDR texture to native colors array.
  85546. */
  85547. var HDRTools = /** @class */ (function () {
  85548. function HDRTools() {
  85549. }
  85550. HDRTools.Ldexp = function (mantissa, exponent) {
  85551. if (exponent > 1023) {
  85552. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  85553. }
  85554. if (exponent < -1074) {
  85555. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  85556. }
  85557. return mantissa * Math.pow(2, exponent);
  85558. };
  85559. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  85560. if (exponent > 0) { /*nonzero pixel*/
  85561. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  85562. float32array[index + 0] = red * exponent;
  85563. float32array[index + 1] = green * exponent;
  85564. float32array[index + 2] = blue * exponent;
  85565. }
  85566. else {
  85567. float32array[index + 0] = 0;
  85568. float32array[index + 1] = 0;
  85569. float32array[index + 2] = 0;
  85570. }
  85571. };
  85572. HDRTools.readStringLine = function (uint8array, startIndex) {
  85573. var line = "";
  85574. var character = "";
  85575. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  85576. character = String.fromCharCode(uint8array[i]);
  85577. if (character == "\n") {
  85578. break;
  85579. }
  85580. line += character;
  85581. }
  85582. return line;
  85583. };
  85584. /**
  85585. * Reads header information from an RGBE texture stored in a native array.
  85586. * More information on this format are available here:
  85587. * https://en.wikipedia.org/wiki/RGBE_image_format
  85588. *
  85589. * @param uint8array The binary file stored in native array.
  85590. * @return The header information.
  85591. */
  85592. HDRTools.RGBE_ReadHeader = function (uint8array) {
  85593. var height = 0;
  85594. var width = 0;
  85595. var line = this.readStringLine(uint8array, 0);
  85596. if (line[0] != '#' || line[1] != '?') {
  85597. throw "Bad HDR Format.";
  85598. }
  85599. var endOfHeader = false;
  85600. var findFormat = false;
  85601. var lineIndex = 0;
  85602. do {
  85603. lineIndex += (line.length + 1);
  85604. line = this.readStringLine(uint8array, lineIndex);
  85605. if (line == "FORMAT=32-bit_rle_rgbe") {
  85606. findFormat = true;
  85607. }
  85608. else if (line.length == 0) {
  85609. endOfHeader = true;
  85610. }
  85611. } while (!endOfHeader);
  85612. if (!findFormat) {
  85613. throw "HDR Bad header format, unsupported FORMAT";
  85614. }
  85615. lineIndex += (line.length + 1);
  85616. line = this.readStringLine(uint8array, lineIndex);
  85617. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  85618. var match = sizeRegexp.exec(line);
  85619. // TODO. Support +Y and -X if needed.
  85620. if (!match || match.length < 3) {
  85621. throw "HDR Bad header format, no size";
  85622. }
  85623. width = parseInt(match[2]);
  85624. height = parseInt(match[1]);
  85625. if (width < 8 || width > 0x7fff) {
  85626. throw "HDR Bad header format, unsupported size";
  85627. }
  85628. lineIndex += (line.length + 1);
  85629. return {
  85630. height: height,
  85631. width: width,
  85632. dataPosition: lineIndex
  85633. };
  85634. };
  85635. /**
  85636. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  85637. * This RGBE texture needs to store the information as a panorama.
  85638. *
  85639. * More information on this format are available here:
  85640. * https://en.wikipedia.org/wiki/RGBE_image_format
  85641. *
  85642. * @param buffer The binary file stored in an array buffer.
  85643. * @param size The expected size of the extracted cubemap.
  85644. * @return The Cube Map information.
  85645. */
  85646. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  85647. var uint8array = new Uint8Array(buffer);
  85648. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  85649. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85650. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  85651. return cubeMapData;
  85652. };
  85653. /**
  85654. * Returns the pixels data extracted from an RGBE texture.
  85655. * This pixels will be stored left to right up to down in the R G B order in one array.
  85656. *
  85657. * More information on this format are available here:
  85658. * https://en.wikipedia.org/wiki/RGBE_image_format
  85659. *
  85660. * @param uint8array The binary file stored in an array buffer.
  85661. * @param hdrInfo The header information of the file.
  85662. * @return The pixels data in RGB right to left up to down order.
  85663. */
  85664. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  85665. // Keep for multi format supports.
  85666. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85667. };
  85668. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  85669. var num_scanlines = hdrInfo.height;
  85670. var scanline_width = hdrInfo.width;
  85671. var a, b, c, d, count;
  85672. var dataIndex = hdrInfo.dataPosition;
  85673. var index = 0, endIndex = 0, i = 0;
  85674. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  85675. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  85676. // 3 channels of 4 bytes per pixel in float.
  85677. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  85678. var resultArray = new Float32Array(resultBuffer);
  85679. // read in each successive scanline
  85680. while (num_scanlines > 0) {
  85681. a = uint8array[dataIndex++];
  85682. b = uint8array[dataIndex++];
  85683. c = uint8array[dataIndex++];
  85684. d = uint8array[dataIndex++];
  85685. if (a != 2 || b != 2 || (c & 0x80)) {
  85686. // this file is not run length encoded
  85687. throw "HDR Bad header format, not RLE";
  85688. }
  85689. if (((c << 8) | d) != scanline_width) {
  85690. throw "HDR Bad header format, wrong scan line width";
  85691. }
  85692. index = 0;
  85693. // read each of the four channels for the scanline into the buffer
  85694. for (i = 0; i < 4; i++) {
  85695. endIndex = (i + 1) * scanline_width;
  85696. while (index < endIndex) {
  85697. a = uint8array[dataIndex++];
  85698. b = uint8array[dataIndex++];
  85699. if (a > 128) {
  85700. // a run of the same value
  85701. count = a - 128;
  85702. if ((count == 0) || (count > endIndex - index)) {
  85703. throw "HDR Bad Format, bad scanline data (run)";
  85704. }
  85705. while (count-- > 0) {
  85706. scanLineArray[index++] = b;
  85707. }
  85708. }
  85709. else {
  85710. // a non-run
  85711. count = a;
  85712. if ((count == 0) || (count > endIndex - index)) {
  85713. throw "HDR Bad Format, bad scanline data (non-run)";
  85714. }
  85715. scanLineArray[index++] = b;
  85716. if (--count > 0) {
  85717. for (var j = 0; j < count; j++) {
  85718. scanLineArray[index++] = uint8array[dataIndex++];
  85719. }
  85720. }
  85721. }
  85722. }
  85723. }
  85724. // now convert data from buffer into floats
  85725. for (i = 0; i < scanline_width; i++) {
  85726. a = scanLineArray[i];
  85727. b = scanLineArray[i + scanline_width];
  85728. c = scanLineArray[i + 2 * scanline_width];
  85729. d = scanLineArray[i + 3 * scanline_width];
  85730. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85731. }
  85732. num_scanlines--;
  85733. }
  85734. return resultArray;
  85735. };
  85736. return HDRTools;
  85737. }());
  85738. BABYLON.HDRTools = HDRTools;
  85739. })(BABYLON || (BABYLON = {}));
  85740. //# sourceMappingURL=babylon.hdr.js.map
  85741. var BABYLON;
  85742. (function (BABYLON) {
  85743. /**
  85744. * This represents a texture coming from an HDR input.
  85745. *
  85746. * The only supported format is currently panorama picture stored in RGBE format.
  85747. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85748. */
  85749. var HDRCubeTexture = /** @class */ (function (_super) {
  85750. __extends(HDRCubeTexture, _super);
  85751. /**
  85752. * Instantiates an HDRTexture from the following parameters.
  85753. *
  85754. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85755. * @param scene The scene the texture will be used in
  85756. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85757. * @param noMipmap Forces to not generate the mipmap if true
  85758. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85759. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  85760. * @param reserved Reserved flag for internal use.
  85761. */
  85762. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85763. if (noMipmap === void 0) { noMipmap = false; }
  85764. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85765. if (gammaSpace === void 0) { gammaSpace = false; }
  85766. if (reserved === void 0) { reserved = false; }
  85767. if (onLoad === void 0) { onLoad = null; }
  85768. if (onError === void 0) { onError = null; }
  85769. var _this = _super.call(this, scene) || this;
  85770. _this._generateHarmonics = true;
  85771. _this._onLoad = null;
  85772. _this._onError = null;
  85773. /**
  85774. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85775. */
  85776. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85777. _this._isBlocking = true;
  85778. _this._rotationY = 0;
  85779. /**
  85780. * Gets or sets the center of the bounding box associated with the cube texture
  85781. * It must define where the camera used to render the texture was set
  85782. */
  85783. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  85784. if (!url) {
  85785. return _this;
  85786. }
  85787. _this.name = url;
  85788. _this.url = url;
  85789. _this.hasAlpha = false;
  85790. _this.isCube = true;
  85791. _this._textureMatrix = BABYLON.Matrix.Identity();
  85792. _this._onLoad = onLoad;
  85793. _this._onError = onError;
  85794. _this.gammaSpace = gammaSpace;
  85795. _this._noMipmap = noMipmap;
  85796. _this._size = size;
  85797. _this._texture = _this._getFromCache(url, _this._noMipmap);
  85798. if (!_this._texture) {
  85799. if (!scene.useDelayedTextureLoading) {
  85800. _this.loadTexture();
  85801. }
  85802. else {
  85803. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85804. }
  85805. }
  85806. return _this;
  85807. }
  85808. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  85809. /**
  85810. * Gets wether or not the texture is blocking during loading.
  85811. */
  85812. get: function () {
  85813. return this._isBlocking;
  85814. },
  85815. /**
  85816. * Sets wether or not the texture is blocking during loading.
  85817. */
  85818. set: function (value) {
  85819. this._isBlocking = value;
  85820. },
  85821. enumerable: true,
  85822. configurable: true
  85823. });
  85824. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  85825. /**
  85826. * Gets texture matrix rotation angle around Y axis radians.
  85827. */
  85828. get: function () {
  85829. return this._rotationY;
  85830. },
  85831. /**
  85832. * Sets texture matrix rotation angle around Y axis in radians.
  85833. */
  85834. set: function (value) {
  85835. this._rotationY = value;
  85836. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  85837. },
  85838. enumerable: true,
  85839. configurable: true
  85840. });
  85841. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  85842. get: function () {
  85843. return this._boundingBoxSize;
  85844. },
  85845. /**
  85846. * Gets or sets the size of the bounding box associated with the cube texture
  85847. * When defined, the cubemap will switch to local mode
  85848. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  85849. * @example https://www.babylonjs-playground.com/#RNASML
  85850. */
  85851. set: function (value) {
  85852. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  85853. return;
  85854. }
  85855. this._boundingBoxSize = value;
  85856. var scene = this.getScene();
  85857. if (scene) {
  85858. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  85859. }
  85860. },
  85861. enumerable: true,
  85862. configurable: true
  85863. });
  85864. /**
  85865. * Occurs when the file is raw .hdr file.
  85866. */
  85867. HDRCubeTexture.prototype.loadTexture = function () {
  85868. var _this = this;
  85869. var callback = function (buffer) {
  85870. _this.lodGenerationOffset = 0.0;
  85871. _this.lodGenerationScale = 0.8;
  85872. var scene = _this.getScene();
  85873. if (!scene) {
  85874. return null;
  85875. }
  85876. // Extract the raw linear data.
  85877. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  85878. // Generate harmonics if needed.
  85879. if (_this._generateHarmonics) {
  85880. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  85881. _this.sphericalPolynomial = sphericalPolynomial;
  85882. }
  85883. var results = [];
  85884. var byteArray = null;
  85885. // Push each faces.
  85886. for (var j = 0; j < 6; j++) {
  85887. // Create uintarray fallback.
  85888. if (!scene.getEngine().getCaps().textureFloat) {
  85889. // 3 channels of 1 bytes per pixel in bytes.
  85890. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  85891. byteArray = new Uint8Array(byteBuffer);
  85892. }
  85893. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  85894. // If special cases.
  85895. if (_this.gammaSpace || byteArray) {
  85896. for (var i = 0; i < _this._size * _this._size; i++) {
  85897. // Put in gamma space if requested.
  85898. if (_this.gammaSpace) {
  85899. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  85900. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  85901. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  85902. }
  85903. // Convert to int texture for fallback.
  85904. if (byteArray) {
  85905. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  85906. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  85907. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  85908. // May use luminance instead if the result is not accurate.
  85909. var max = Math.max(Math.max(r, g), b);
  85910. if (max > 255) {
  85911. var scale = 255 / max;
  85912. r *= scale;
  85913. g *= scale;
  85914. b *= scale;
  85915. }
  85916. byteArray[(i * 3) + 0] = r;
  85917. byteArray[(i * 3) + 1] = g;
  85918. byteArray[(i * 3) + 2] = b;
  85919. }
  85920. }
  85921. }
  85922. if (byteArray) {
  85923. results.push(byteArray);
  85924. }
  85925. else {
  85926. results.push(dataFace);
  85927. }
  85928. }
  85929. return results;
  85930. };
  85931. var scene = this.getScene();
  85932. if (scene) {
  85933. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  85934. }
  85935. };
  85936. HDRCubeTexture.prototype.clone = function () {
  85937. var scene = this.getScene();
  85938. if (!scene) {
  85939. return this;
  85940. }
  85941. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85942. // Base texture
  85943. newTexture.level = this.level;
  85944. newTexture.wrapU = this.wrapU;
  85945. newTexture.wrapV = this.wrapV;
  85946. newTexture.coordinatesIndex = this.coordinatesIndex;
  85947. newTexture.coordinatesMode = this.coordinatesMode;
  85948. return newTexture;
  85949. };
  85950. // Methods
  85951. HDRCubeTexture.prototype.delayLoad = function () {
  85952. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85953. return;
  85954. }
  85955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85956. this._texture = this._getFromCache(this.url, this._noMipmap);
  85957. if (!this._texture) {
  85958. this.loadTexture();
  85959. }
  85960. };
  85961. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85962. return this._textureMatrix;
  85963. };
  85964. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85965. this._textureMatrix = value;
  85966. };
  85967. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85968. var texture = null;
  85969. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85970. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85971. texture.name = parsedTexture.name;
  85972. texture.hasAlpha = parsedTexture.hasAlpha;
  85973. texture.level = parsedTexture.level;
  85974. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85975. texture.isBlocking = parsedTexture.isBlocking;
  85976. }
  85977. if (texture) {
  85978. if (parsedTexture.boundingBoxPosition) {
  85979. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85980. }
  85981. if (parsedTexture.boundingBoxSize) {
  85982. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85983. }
  85984. if (parsedTexture.rotationY) {
  85985. texture.rotationY = parsedTexture.rotationY;
  85986. }
  85987. }
  85988. return texture;
  85989. };
  85990. HDRCubeTexture.prototype.serialize = function () {
  85991. if (!this.name) {
  85992. return null;
  85993. }
  85994. var serializationObject = {};
  85995. serializationObject.name = this.name;
  85996. serializationObject.hasAlpha = this.hasAlpha;
  85997. serializationObject.isCube = true;
  85998. serializationObject.level = this.level;
  85999. serializationObject.size = this._size;
  86000. serializationObject.coordinatesMode = this.coordinatesMode;
  86001. serializationObject.useInGammaSpace = this.gammaSpace;
  86002. serializationObject.generateHarmonics = this._generateHarmonics;
  86003. serializationObject.customType = "BABYLON.HDRCubeTexture";
  86004. serializationObject.noMipmap = this._noMipmap;
  86005. serializationObject.isBlocking = this._isBlocking;
  86006. serializationObject.rotationY = this._rotationY;
  86007. return serializationObject;
  86008. };
  86009. HDRCubeTexture._facesMapping = [
  86010. "right",
  86011. "left",
  86012. "up",
  86013. "down",
  86014. "front",
  86015. "back"
  86016. ];
  86017. return HDRCubeTexture;
  86018. }(BABYLON.BaseTexture));
  86019. BABYLON.HDRCubeTexture = HDRCubeTexture;
  86020. })(BABYLON || (BABYLON = {}));
  86021. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  86022. var BABYLON;
  86023. (function (BABYLON) {
  86024. /**
  86025. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  86026. */
  86027. var PanoramaToCubeMapTools = /** @class */ (function () {
  86028. function PanoramaToCubeMapTools() {
  86029. }
  86030. /**
  86031. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  86032. *
  86033. * @param float32Array The source data.
  86034. * @param inputWidth The width of the input panorama.
  86035. * @param inputhHeight The height of the input panorama.
  86036. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  86037. * @return The cubemap data
  86038. */
  86039. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  86040. if (!float32Array) {
  86041. throw "ConvertPanoramaToCubemap: input cannot be null";
  86042. }
  86043. if (float32Array.length != inputWidth * inputHeight * 3) {
  86044. throw "ConvertPanoramaToCubemap: input size is wrong";
  86045. }
  86046. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  86047. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  86048. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  86049. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  86050. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  86051. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  86052. return {
  86053. front: textureFront,
  86054. back: textureBack,
  86055. left: textureLeft,
  86056. right: textureRight,
  86057. up: textureUp,
  86058. down: textureDown,
  86059. size: size,
  86060. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86061. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  86062. gammaSpace: false,
  86063. };
  86064. };
  86065. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  86066. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  86067. var textureArray = new Float32Array(buffer);
  86068. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  86069. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  86070. var dy = 1 / texSize;
  86071. var fy = 0;
  86072. for (var y = 0; y < texSize; y++) {
  86073. var xv1 = faceData[0];
  86074. var xv2 = faceData[2];
  86075. for (var x = 0; x < texSize; x++) {
  86076. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  86077. v.normalize();
  86078. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  86079. // 3 channels per pixels
  86080. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  86081. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  86082. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  86083. xv1 = xv1.add(rotDX1);
  86084. xv2 = xv2.add(rotDX2);
  86085. }
  86086. fy += dy;
  86087. }
  86088. return textureArray;
  86089. };
  86090. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  86091. var theta = Math.atan2(vDir.z, vDir.x);
  86092. var phi = Math.acos(vDir.y);
  86093. while (theta < -Math.PI)
  86094. theta += 2 * Math.PI;
  86095. while (theta > Math.PI)
  86096. theta -= 2 * Math.PI;
  86097. var dx = theta / Math.PI;
  86098. var dy = phi / Math.PI;
  86099. // recenter.
  86100. dx = dx * 0.5 + 0.5;
  86101. var px = Math.round(dx * inputWidth);
  86102. if (px < 0)
  86103. px = 0;
  86104. else if (px >= inputWidth)
  86105. px = inputWidth - 1;
  86106. var py = Math.round(dy * inputHeight);
  86107. if (py < 0)
  86108. py = 0;
  86109. else if (py >= inputHeight)
  86110. py = inputHeight - 1;
  86111. var inputY = (inputHeight - py - 1);
  86112. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  86113. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  86114. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  86115. return {
  86116. r: r,
  86117. g: g,
  86118. b: b
  86119. };
  86120. };
  86121. PanoramaToCubeMapTools.FACE_FRONT = [
  86122. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86123. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86124. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86125. new BABYLON.Vector3(1.0, 1.0, -1.0)
  86126. ];
  86127. PanoramaToCubeMapTools.FACE_BACK = [
  86128. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86129. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86130. new BABYLON.Vector3(1.0, 1.0, 1.0),
  86131. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  86132. ];
  86133. PanoramaToCubeMapTools.FACE_RIGHT = [
  86134. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86135. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86136. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86137. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86138. ];
  86139. PanoramaToCubeMapTools.FACE_LEFT = [
  86140. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86141. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86142. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86143. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  86144. ];
  86145. PanoramaToCubeMapTools.FACE_DOWN = [
  86146. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86147. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86148. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86149. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86150. ];
  86151. PanoramaToCubeMapTools.FACE_UP = [
  86152. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86153. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86154. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86155. new BABYLON.Vector3(1.0, -1.0, -1.0)
  86156. ];
  86157. return PanoramaToCubeMapTools;
  86158. }());
  86159. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  86160. })(BABYLON || (BABYLON = {}));
  86161. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  86162. var BABYLON;
  86163. (function (BABYLON) {
  86164. var IndexedVector2 = /** @class */ (function (_super) {
  86165. __extends(IndexedVector2, _super);
  86166. function IndexedVector2(original, index) {
  86167. var _this = _super.call(this, original.x, original.y) || this;
  86168. _this.index = index;
  86169. return _this;
  86170. }
  86171. return IndexedVector2;
  86172. }(BABYLON.Vector2));
  86173. var PolygonPoints = /** @class */ (function () {
  86174. function PolygonPoints() {
  86175. this.elements = new Array();
  86176. }
  86177. PolygonPoints.prototype.add = function (originalPoints) {
  86178. var _this = this;
  86179. var result = new Array();
  86180. originalPoints.forEach(function (point) {
  86181. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  86182. var newPoint = new IndexedVector2(point, _this.elements.length);
  86183. result.push(newPoint);
  86184. _this.elements.push(newPoint);
  86185. }
  86186. });
  86187. return result;
  86188. };
  86189. PolygonPoints.prototype.computeBounds = function () {
  86190. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86191. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86192. this.elements.forEach(function (point) {
  86193. // x
  86194. if (point.x < lmin.x) {
  86195. lmin.x = point.x;
  86196. }
  86197. else if (point.x > lmax.x) {
  86198. lmax.x = point.x;
  86199. }
  86200. // y
  86201. if (point.y < lmin.y) {
  86202. lmin.y = point.y;
  86203. }
  86204. else if (point.y > lmax.y) {
  86205. lmax.y = point.y;
  86206. }
  86207. });
  86208. return {
  86209. min: lmin,
  86210. max: lmax,
  86211. width: lmax.x - lmin.x,
  86212. height: lmax.y - lmin.y
  86213. };
  86214. };
  86215. return PolygonPoints;
  86216. }());
  86217. var Polygon = /** @class */ (function () {
  86218. function Polygon() {
  86219. }
  86220. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  86221. return [
  86222. new BABYLON.Vector2(xmin, ymin),
  86223. new BABYLON.Vector2(xmax, ymin),
  86224. new BABYLON.Vector2(xmax, ymax),
  86225. new BABYLON.Vector2(xmin, ymax)
  86226. ];
  86227. };
  86228. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  86229. if (cx === void 0) { cx = 0; }
  86230. if (cy === void 0) { cy = 0; }
  86231. if (numberOfSides === void 0) { numberOfSides = 32; }
  86232. var result = new Array();
  86233. var angle = 0;
  86234. var increment = (Math.PI * 2) / numberOfSides;
  86235. for (var i = 0; i < numberOfSides; i++) {
  86236. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  86237. angle -= increment;
  86238. }
  86239. return result;
  86240. };
  86241. Polygon.Parse = function (input) {
  86242. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  86243. var i, result = [];
  86244. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  86245. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  86246. }
  86247. return result;
  86248. };
  86249. Polygon.StartingAt = function (x, y) {
  86250. return BABYLON.Path2.StartingAt(x, y);
  86251. };
  86252. return Polygon;
  86253. }());
  86254. BABYLON.Polygon = Polygon;
  86255. var PolygonMeshBuilder = /** @class */ (function () {
  86256. function PolygonMeshBuilder(name, contours, scene) {
  86257. this._points = new PolygonPoints();
  86258. this._outlinepoints = new PolygonPoints();
  86259. this._holes = new Array();
  86260. this._epoints = new Array();
  86261. this._eholes = new Array();
  86262. this._name = name;
  86263. this._scene = scene;
  86264. var points;
  86265. if (contours instanceof BABYLON.Path2) {
  86266. points = contours.getPoints();
  86267. }
  86268. else {
  86269. points = contours;
  86270. }
  86271. this._addToepoint(points);
  86272. this._points.add(points);
  86273. this._outlinepoints.add(points);
  86274. if (typeof earcut === 'undefined') {
  86275. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  86276. }
  86277. }
  86278. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  86279. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  86280. var p = points_1[_i];
  86281. this._epoints.push(p.x, p.y);
  86282. }
  86283. };
  86284. PolygonMeshBuilder.prototype.addHole = function (hole) {
  86285. this._points.add(hole);
  86286. var holepoints = new PolygonPoints();
  86287. holepoints.add(hole);
  86288. this._holes.push(holepoints);
  86289. this._eholes.push(this._epoints.length / 2);
  86290. this._addToepoint(hole);
  86291. return this;
  86292. };
  86293. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  86294. var _this = this;
  86295. if (updatable === void 0) { updatable = false; }
  86296. if (depth === void 0) { depth = 0; }
  86297. var result = new BABYLON.Mesh(this._name, this._scene);
  86298. var normals = new Array();
  86299. var positions = new Array();
  86300. var uvs = new Array();
  86301. var bounds = this._points.computeBounds();
  86302. this._points.elements.forEach(function (p) {
  86303. normals.push(0, 1.0, 0);
  86304. positions.push(p.x, 0, p.y);
  86305. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  86306. });
  86307. var indices = new Array();
  86308. var res = earcut(this._epoints, this._eholes, 2);
  86309. for (var i = 0; i < res.length; i++) {
  86310. indices.push(res[i]);
  86311. }
  86312. if (depth > 0) {
  86313. var positionscount = (positions.length / 3); //get the current pointcount
  86314. this._points.elements.forEach(function (p) {
  86315. normals.push(0, -1.0, 0);
  86316. positions.push(p.x, -depth, p.y);
  86317. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  86318. });
  86319. var totalCount = indices.length;
  86320. for (var i = 0; i < totalCount; i += 3) {
  86321. var i0 = indices[i + 0];
  86322. var i1 = indices[i + 1];
  86323. var i2 = indices[i + 2];
  86324. indices.push(i2 + positionscount);
  86325. indices.push(i1 + positionscount);
  86326. indices.push(i0 + positionscount);
  86327. }
  86328. //Add the sides
  86329. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  86330. this._holes.forEach(function (hole) {
  86331. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  86332. });
  86333. }
  86334. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  86335. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  86336. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  86337. result.setIndices(indices);
  86338. return result;
  86339. };
  86340. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  86341. var StartIndex = positions.length / 3;
  86342. var ulength = 0;
  86343. for (var i = 0; i < points.elements.length; i++) {
  86344. var p = points.elements[i];
  86345. var p1;
  86346. if ((i + 1) > points.elements.length - 1) {
  86347. p1 = points.elements[0];
  86348. }
  86349. else {
  86350. p1 = points.elements[i + 1];
  86351. }
  86352. positions.push(p.x, 0, p.y);
  86353. positions.push(p.x, -depth, p.y);
  86354. positions.push(p1.x, 0, p1.y);
  86355. positions.push(p1.x, -depth, p1.y);
  86356. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  86357. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  86358. var v3 = v2.subtract(v1);
  86359. var v4 = new BABYLON.Vector3(0, 1, 0);
  86360. var vn = BABYLON.Vector3.Cross(v3, v4);
  86361. vn = vn.normalize();
  86362. uvs.push(ulength / bounds.width, 0);
  86363. uvs.push(ulength / bounds.width, 1);
  86364. ulength += v3.length();
  86365. uvs.push((ulength / bounds.width), 0);
  86366. uvs.push((ulength / bounds.width), 1);
  86367. if (!flip) {
  86368. normals.push(-vn.x, -vn.y, -vn.z);
  86369. normals.push(-vn.x, -vn.y, -vn.z);
  86370. normals.push(-vn.x, -vn.y, -vn.z);
  86371. normals.push(-vn.x, -vn.y, -vn.z);
  86372. indices.push(StartIndex);
  86373. indices.push(StartIndex + 1);
  86374. indices.push(StartIndex + 2);
  86375. indices.push(StartIndex + 1);
  86376. indices.push(StartIndex + 3);
  86377. indices.push(StartIndex + 2);
  86378. }
  86379. else {
  86380. normals.push(vn.x, vn.y, vn.z);
  86381. normals.push(vn.x, vn.y, vn.z);
  86382. normals.push(vn.x, vn.y, vn.z);
  86383. normals.push(vn.x, vn.y, vn.z);
  86384. indices.push(StartIndex);
  86385. indices.push(StartIndex + 2);
  86386. indices.push(StartIndex + 1);
  86387. indices.push(StartIndex + 1);
  86388. indices.push(StartIndex + 2);
  86389. indices.push(StartIndex + 3);
  86390. }
  86391. StartIndex += 4;
  86392. }
  86393. ;
  86394. };
  86395. return PolygonMeshBuilder;
  86396. }());
  86397. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  86398. })(BABYLON || (BABYLON = {}));
  86399. //# sourceMappingURL=babylon.polygonMesh.js.map
  86400. var BABYLON;
  86401. (function (BABYLON) {
  86402. // Unique ID when we import meshes from Babylon to CSG
  86403. var currentCSGMeshId = 0;
  86404. // # class Vertex
  86405. // Represents a vertex of a polygon. Use your own vertex class instead of this
  86406. // one to provide additional features like texture coordinates and vertex
  86407. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  86408. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  86409. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  86410. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  86411. // is not used anywhere else.
  86412. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  86413. var Vertex = /** @class */ (function () {
  86414. function Vertex(pos, normal, uv) {
  86415. this.pos = pos;
  86416. this.normal = normal;
  86417. this.uv = uv;
  86418. }
  86419. Vertex.prototype.clone = function () {
  86420. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  86421. };
  86422. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  86423. // orientation of a polygon is flipped.
  86424. Vertex.prototype.flip = function () {
  86425. this.normal = this.normal.scale(-1);
  86426. };
  86427. // Create a new vertex between this vertex and `other` by linearly
  86428. // interpolating all properties using a parameter of `t`. Subclasses should
  86429. // override this to interpolate additional properties.
  86430. Vertex.prototype.interpolate = function (other, t) {
  86431. 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));
  86432. };
  86433. return Vertex;
  86434. }());
  86435. // # class Plane
  86436. // Represents a plane in 3D space.
  86437. var Plane = /** @class */ (function () {
  86438. function Plane(normal, w) {
  86439. this.normal = normal;
  86440. this.w = w;
  86441. }
  86442. Plane.FromPoints = function (a, b, c) {
  86443. var v0 = c.subtract(a);
  86444. var v1 = b.subtract(a);
  86445. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  86446. return null;
  86447. }
  86448. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  86449. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  86450. };
  86451. Plane.prototype.clone = function () {
  86452. return new Plane(this.normal.clone(), this.w);
  86453. };
  86454. Plane.prototype.flip = function () {
  86455. this.normal.scaleInPlace(-1);
  86456. this.w = -this.w;
  86457. };
  86458. // Split `polygon` by this plane if needed, then put the polygon or polygon
  86459. // fragments in the appropriate lists. Coplanar polygons go into either
  86460. // `coplanarFront` or `coplanarBack` depending on their orientation with
  86461. // respect to this plane. Polygons in front or in back of this plane go into
  86462. // either `front` or `back`.
  86463. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  86464. var COPLANAR = 0;
  86465. var FRONT = 1;
  86466. var BACK = 2;
  86467. var SPANNING = 3;
  86468. // Classify each point as well as the entire polygon into one of the above
  86469. // four classes.
  86470. var polygonType = 0;
  86471. var types = [];
  86472. var i;
  86473. var t;
  86474. for (i = 0; i < polygon.vertices.length; i++) {
  86475. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  86476. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  86477. polygonType |= type;
  86478. types.push(type);
  86479. }
  86480. // Put the polygon in the correct list, splitting it when necessary.
  86481. switch (polygonType) {
  86482. case COPLANAR:
  86483. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  86484. break;
  86485. case FRONT:
  86486. front.push(polygon);
  86487. break;
  86488. case BACK:
  86489. back.push(polygon);
  86490. break;
  86491. case SPANNING:
  86492. var f = [], b = [];
  86493. for (i = 0; i < polygon.vertices.length; i++) {
  86494. var j = (i + 1) % polygon.vertices.length;
  86495. var ti = types[i], tj = types[j];
  86496. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  86497. if (ti !== BACK)
  86498. f.push(vi);
  86499. if (ti !== FRONT)
  86500. b.push(ti !== BACK ? vi.clone() : vi);
  86501. if ((ti | tj) === SPANNING) {
  86502. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  86503. var v = vi.interpolate(vj, t);
  86504. f.push(v);
  86505. b.push(v.clone());
  86506. }
  86507. }
  86508. var poly;
  86509. if (f.length >= 3) {
  86510. poly = new Polygon(f, polygon.shared);
  86511. if (poly.plane)
  86512. front.push(poly);
  86513. }
  86514. if (b.length >= 3) {
  86515. poly = new Polygon(b, polygon.shared);
  86516. if (poly.plane)
  86517. back.push(poly);
  86518. }
  86519. break;
  86520. }
  86521. };
  86522. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  86523. // point is on the plane.
  86524. Plane.EPSILON = 1e-5;
  86525. return Plane;
  86526. }());
  86527. // # class Polygon
  86528. // Represents a convex polygon. The vertices used to initialize a polygon must
  86529. // be coplanar and form a convex loop.
  86530. //
  86531. // Each convex polygon has a `shared` property, which is shared between all
  86532. // polygons that are clones of each other or were split from the same polygon.
  86533. // This can be used to define per-polygon properties (such as surface color).
  86534. var Polygon = /** @class */ (function () {
  86535. function Polygon(vertices, shared) {
  86536. this.vertices = vertices;
  86537. this.shared = shared;
  86538. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  86539. }
  86540. Polygon.prototype.clone = function () {
  86541. var vertices = this.vertices.map(function (v) { return v.clone(); });
  86542. return new Polygon(vertices, this.shared);
  86543. };
  86544. Polygon.prototype.flip = function () {
  86545. this.vertices.reverse().map(function (v) { v.flip(); });
  86546. this.plane.flip();
  86547. };
  86548. return Polygon;
  86549. }());
  86550. // # class Node
  86551. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  86552. // by picking a polygon to split along. That polygon (and all other coplanar
  86553. // polygons) are added directly to that node and the other polygons are added to
  86554. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  86555. // no distinction between internal and leaf nodes.
  86556. var Node = /** @class */ (function () {
  86557. function Node(polygons) {
  86558. this.plane = null;
  86559. this.front = null;
  86560. this.back = null;
  86561. this.polygons = new Array();
  86562. if (polygons) {
  86563. this.build(polygons);
  86564. }
  86565. }
  86566. Node.prototype.clone = function () {
  86567. var node = new Node();
  86568. node.plane = this.plane && this.plane.clone();
  86569. node.front = this.front && this.front.clone();
  86570. node.back = this.back && this.back.clone();
  86571. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  86572. return node;
  86573. };
  86574. // Convert solid space to empty space and empty space to solid space.
  86575. Node.prototype.invert = function () {
  86576. for (var i = 0; i < this.polygons.length; i++) {
  86577. this.polygons[i].flip();
  86578. }
  86579. if (this.plane) {
  86580. this.plane.flip();
  86581. }
  86582. if (this.front) {
  86583. this.front.invert();
  86584. }
  86585. if (this.back) {
  86586. this.back.invert();
  86587. }
  86588. var temp = this.front;
  86589. this.front = this.back;
  86590. this.back = temp;
  86591. };
  86592. // Recursively remove all polygons in `polygons` that are inside this BSP
  86593. // tree.
  86594. Node.prototype.clipPolygons = function (polygons) {
  86595. if (!this.plane)
  86596. return polygons.slice();
  86597. var front = new Array(), back = new Array();
  86598. for (var i = 0; i < polygons.length; i++) {
  86599. this.plane.splitPolygon(polygons[i], front, back, front, back);
  86600. }
  86601. if (this.front) {
  86602. front = this.front.clipPolygons(front);
  86603. }
  86604. if (this.back) {
  86605. back = this.back.clipPolygons(back);
  86606. }
  86607. else {
  86608. back = [];
  86609. }
  86610. return front.concat(back);
  86611. };
  86612. // Remove all polygons in this BSP tree that are inside the other BSP tree
  86613. // `bsp`.
  86614. Node.prototype.clipTo = function (bsp) {
  86615. this.polygons = bsp.clipPolygons(this.polygons);
  86616. if (this.front)
  86617. this.front.clipTo(bsp);
  86618. if (this.back)
  86619. this.back.clipTo(bsp);
  86620. };
  86621. // Return a list of all polygons in this BSP tree.
  86622. Node.prototype.allPolygons = function () {
  86623. var polygons = this.polygons.slice();
  86624. if (this.front)
  86625. polygons = polygons.concat(this.front.allPolygons());
  86626. if (this.back)
  86627. polygons = polygons.concat(this.back.allPolygons());
  86628. return polygons;
  86629. };
  86630. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  86631. // new polygons are filtered down to the bottom of the tree and become new
  86632. // nodes there. Each set of polygons is partitioned using the first polygon
  86633. // (no heuristic is used to pick a good split).
  86634. Node.prototype.build = function (polygons) {
  86635. if (!polygons.length)
  86636. return;
  86637. if (!this.plane)
  86638. this.plane = polygons[0].plane.clone();
  86639. var front = new Array(), back = new Array();
  86640. for (var i = 0; i < polygons.length; i++) {
  86641. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  86642. }
  86643. if (front.length) {
  86644. if (!this.front)
  86645. this.front = new Node();
  86646. this.front.build(front);
  86647. }
  86648. if (back.length) {
  86649. if (!this.back)
  86650. this.back = new Node();
  86651. this.back.build(back);
  86652. }
  86653. };
  86654. return Node;
  86655. }());
  86656. var CSG = /** @class */ (function () {
  86657. function CSG() {
  86658. this.polygons = new Array();
  86659. }
  86660. // Convert BABYLON.Mesh to BABYLON.CSG
  86661. CSG.FromMesh = function (mesh) {
  86662. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  86663. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  86664. if (mesh instanceof BABYLON.Mesh) {
  86665. mesh.computeWorldMatrix(true);
  86666. matrix = mesh.getWorldMatrix();
  86667. meshPosition = mesh.position.clone();
  86668. meshRotation = mesh.rotation.clone();
  86669. if (mesh.rotationQuaternion) {
  86670. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  86671. }
  86672. meshScaling = mesh.scaling.clone();
  86673. }
  86674. else {
  86675. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  86676. }
  86677. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  86678. var subMeshes = mesh.subMeshes;
  86679. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  86680. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  86681. vertices = [];
  86682. for (var j = 0; j < 3; j++) {
  86683. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  86684. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  86685. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86686. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86687. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86688. vertex = new Vertex(position, normal, uv);
  86689. vertices.push(vertex);
  86690. }
  86691. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86692. // To handle the case of degenerated triangle
  86693. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86694. if (polygon.plane)
  86695. polygons.push(polygon);
  86696. }
  86697. }
  86698. var csg = CSG.FromPolygons(polygons);
  86699. csg.matrix = matrix;
  86700. csg.position = meshPosition;
  86701. csg.rotation = meshRotation;
  86702. csg.scaling = meshScaling;
  86703. csg.rotationQuaternion = meshRotationQuaternion;
  86704. currentCSGMeshId++;
  86705. return csg;
  86706. };
  86707. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86708. CSG.FromPolygons = function (polygons) {
  86709. var csg = new CSG();
  86710. csg.polygons = polygons;
  86711. return csg;
  86712. };
  86713. CSG.prototype.clone = function () {
  86714. var csg = new CSG();
  86715. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86716. csg.copyTransformAttributes(this);
  86717. return csg;
  86718. };
  86719. CSG.prototype.union = function (csg) {
  86720. var a = new Node(this.clone().polygons);
  86721. var b = new Node(csg.clone().polygons);
  86722. a.clipTo(b);
  86723. b.clipTo(a);
  86724. b.invert();
  86725. b.clipTo(a);
  86726. b.invert();
  86727. a.build(b.allPolygons());
  86728. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86729. };
  86730. CSG.prototype.unionInPlace = function (csg) {
  86731. var a = new Node(this.polygons);
  86732. var b = new Node(csg.polygons);
  86733. a.clipTo(b);
  86734. b.clipTo(a);
  86735. b.invert();
  86736. b.clipTo(a);
  86737. b.invert();
  86738. a.build(b.allPolygons());
  86739. this.polygons = a.allPolygons();
  86740. };
  86741. CSG.prototype.subtract = function (csg) {
  86742. var a = new Node(this.clone().polygons);
  86743. var b = new Node(csg.clone().polygons);
  86744. a.invert();
  86745. a.clipTo(b);
  86746. b.clipTo(a);
  86747. b.invert();
  86748. b.clipTo(a);
  86749. b.invert();
  86750. a.build(b.allPolygons());
  86751. a.invert();
  86752. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86753. };
  86754. CSG.prototype.subtractInPlace = function (csg) {
  86755. var a = new Node(this.polygons);
  86756. var b = new Node(csg.polygons);
  86757. a.invert();
  86758. a.clipTo(b);
  86759. b.clipTo(a);
  86760. b.invert();
  86761. b.clipTo(a);
  86762. b.invert();
  86763. a.build(b.allPolygons());
  86764. a.invert();
  86765. this.polygons = a.allPolygons();
  86766. };
  86767. CSG.prototype.intersect = function (csg) {
  86768. var a = new Node(this.clone().polygons);
  86769. var b = new Node(csg.clone().polygons);
  86770. a.invert();
  86771. b.clipTo(a);
  86772. b.invert();
  86773. a.clipTo(b);
  86774. b.clipTo(a);
  86775. a.build(b.allPolygons());
  86776. a.invert();
  86777. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86778. };
  86779. CSG.prototype.intersectInPlace = function (csg) {
  86780. var a = new Node(this.polygons);
  86781. var b = new Node(csg.polygons);
  86782. a.invert();
  86783. b.clipTo(a);
  86784. b.invert();
  86785. a.clipTo(b);
  86786. b.clipTo(a);
  86787. a.build(b.allPolygons());
  86788. a.invert();
  86789. this.polygons = a.allPolygons();
  86790. };
  86791. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  86792. // not modified.
  86793. CSG.prototype.inverse = function () {
  86794. var csg = this.clone();
  86795. csg.inverseInPlace();
  86796. return csg;
  86797. };
  86798. CSG.prototype.inverseInPlace = function () {
  86799. this.polygons.map(function (p) { p.flip(); });
  86800. };
  86801. // This is used to keep meshes transformations so they can be restored
  86802. // when we build back a Babylon Mesh
  86803. // NB : All CSG operations are performed in world coordinates
  86804. CSG.prototype.copyTransformAttributes = function (csg) {
  86805. this.matrix = csg.matrix;
  86806. this.position = csg.position;
  86807. this.rotation = csg.rotation;
  86808. this.scaling = csg.scaling;
  86809. this.rotationQuaternion = csg.rotationQuaternion;
  86810. return this;
  86811. };
  86812. // Build Raw mesh from CSG
  86813. // Coordinates here are in world space
  86814. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  86815. var matrix = this.matrix.clone();
  86816. matrix.invert();
  86817. 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;
  86818. if (keepSubMeshes) {
  86819. // Sort Polygons, since subMeshes are indices range
  86820. polygons.sort(function (a, b) {
  86821. if (a.shared.meshId === b.shared.meshId) {
  86822. return a.shared.subMeshId - b.shared.subMeshId;
  86823. }
  86824. else {
  86825. return a.shared.meshId - b.shared.meshId;
  86826. }
  86827. });
  86828. }
  86829. for (var i = 0, il = polygons.length; i < il; i++) {
  86830. polygon = polygons[i];
  86831. // Building SubMeshes
  86832. if (!subMesh_dict[polygon.shared.meshId]) {
  86833. subMesh_dict[polygon.shared.meshId] = {};
  86834. }
  86835. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  86836. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  86837. indexStart: +Infinity,
  86838. indexEnd: -Infinity,
  86839. materialIndex: polygon.shared.materialIndex
  86840. };
  86841. }
  86842. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  86843. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  86844. polygonIndices[0] = 0;
  86845. polygonIndices[1] = j - 1;
  86846. polygonIndices[2] = j;
  86847. for (var k = 0; k < 3; k++) {
  86848. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  86849. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  86850. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  86851. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  86852. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  86853. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  86854. // Check if 2 points can be merged
  86855. if (!(typeof vertex_idx !== 'undefined' &&
  86856. normals[vertex_idx * 3] === localNormal.x &&
  86857. normals[vertex_idx * 3 + 1] === localNormal.y &&
  86858. normals[vertex_idx * 3 + 2] === localNormal.z &&
  86859. uvs[vertex_idx * 2] === uv.x &&
  86860. uvs[vertex_idx * 2 + 1] === uv.y)) {
  86861. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  86862. uvs.push(uv.x, uv.y);
  86863. normals.push(normal.x, normal.y, normal.z);
  86864. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  86865. }
  86866. indices.push(vertex_idx);
  86867. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  86868. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  86869. currentIndex++;
  86870. }
  86871. }
  86872. }
  86873. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  86874. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  86875. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  86876. mesh.setIndices(indices, null);
  86877. if (keepSubMeshes) {
  86878. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  86879. var materialIndexOffset = 0, materialMaxIndex;
  86880. mesh.subMeshes = new Array();
  86881. for (var m in subMesh_dict) {
  86882. materialMaxIndex = -1;
  86883. for (var sm in subMesh_dict[m]) {
  86884. subMesh_obj = subMesh_dict[m][sm];
  86885. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  86886. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  86887. }
  86888. materialIndexOffset += ++materialMaxIndex;
  86889. }
  86890. }
  86891. return mesh;
  86892. };
  86893. // Build Mesh from CSG taking material and transforms into account
  86894. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  86895. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  86896. mesh.material = material;
  86897. mesh.position.copyFrom(this.position);
  86898. mesh.rotation.copyFrom(this.rotation);
  86899. if (this.rotationQuaternion) {
  86900. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  86901. }
  86902. mesh.scaling.copyFrom(this.scaling);
  86903. mesh.computeWorldMatrix(true);
  86904. return mesh;
  86905. };
  86906. return CSG;
  86907. }());
  86908. BABYLON.CSG = CSG;
  86909. })(BABYLON || (BABYLON = {}));
  86910. //# sourceMappingURL=babylon.csg.js.map
  86911. var BABYLON;
  86912. (function (BABYLON) {
  86913. var LensFlare = /** @class */ (function () {
  86914. function LensFlare(size, position, color, imgUrl, system) {
  86915. this.size = size;
  86916. this.position = position;
  86917. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86918. this.color = color || new BABYLON.Color3(1, 1, 1);
  86919. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86920. this._system = system;
  86921. system.lensFlares.push(this);
  86922. }
  86923. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86924. return new LensFlare(size, position, color, imgUrl, system);
  86925. };
  86926. LensFlare.prototype.dispose = function () {
  86927. if (this.texture) {
  86928. this.texture.dispose();
  86929. }
  86930. // Remove from scene
  86931. var index = this._system.lensFlares.indexOf(this);
  86932. this._system.lensFlares.splice(index, 1);
  86933. };
  86934. ;
  86935. return LensFlare;
  86936. }());
  86937. BABYLON.LensFlare = LensFlare;
  86938. })(BABYLON || (BABYLON = {}));
  86939. //# sourceMappingURL=babylon.lensFlare.js.map
  86940. var BABYLON;
  86941. (function (BABYLON) {
  86942. // Adds the parser to the scene parsers.
  86943. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86944. // Lens flares
  86945. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86946. if (!container.lensFlareSystems) {
  86947. container.lensFlareSystems = new Array();
  86948. }
  86949. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86950. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86951. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86952. container.lensFlareSystems.push(lf);
  86953. }
  86954. }
  86955. });
  86956. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86957. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86958. if (this.lensFlareSystems[index].name === name) {
  86959. return this.lensFlareSystems[index];
  86960. }
  86961. }
  86962. return null;
  86963. };
  86964. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86965. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86966. if (this.lensFlareSystems[index].id === id) {
  86967. return this.lensFlareSystems[index];
  86968. }
  86969. }
  86970. return null;
  86971. };
  86972. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86973. var index = this.lensFlareSystems.indexOf(toRemove);
  86974. if (index !== -1) {
  86975. this.lensFlareSystems.splice(index, 1);
  86976. }
  86977. return index;
  86978. };
  86979. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86980. this.lensFlareSystems.push(newLensFlareSystem);
  86981. };
  86982. /**
  86983. * Defines the lens flare scene component responsible to manage any lens flares
  86984. * in a given scene.
  86985. */
  86986. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86987. /**
  86988. * Creates a new instance of the component for the given scene
  86989. * @param scene Defines the scene to register the component in
  86990. */
  86991. function LensFlareSystemSceneComponent(scene) {
  86992. /**
  86993. * The component name helpfull to identify the component in the list of scene components.
  86994. */
  86995. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86996. this.scene = scene;
  86997. scene.lensFlareSystems = new Array();
  86998. }
  86999. /**
  87000. * Registers the component in a given scene
  87001. */
  87002. LensFlareSystemSceneComponent.prototype.register = function () {
  87003. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  87004. };
  87005. /**
  87006. * Rebuilds the elements related to this component in case of
  87007. * context lost for instance.
  87008. */
  87009. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  87010. // Nothing to do for lens flare
  87011. };
  87012. /**
  87013. * Adds all the element from the container to the scene
  87014. * @param container the container holding the elements
  87015. */
  87016. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  87017. var _this = this;
  87018. if (!container.lensFlareSystems) {
  87019. return;
  87020. }
  87021. container.lensFlareSystems.forEach(function (o) {
  87022. _this.scene.addLensFlareSystem(o);
  87023. });
  87024. };
  87025. /**
  87026. * Removes all the elements in the container from the scene
  87027. * @param container contains the elements to remove
  87028. */
  87029. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  87030. var _this = this;
  87031. if (!container.lensFlareSystems) {
  87032. return;
  87033. }
  87034. container.lensFlareSystems.forEach(function (o) {
  87035. _this.scene.removeLensFlareSystem(o);
  87036. });
  87037. };
  87038. /**
  87039. * Serializes the component data to the specified json object
  87040. * @param serializationObject The object to serialize to
  87041. */
  87042. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  87043. // Lens flares
  87044. serializationObject.lensFlareSystems = [];
  87045. var lensFlareSystems = this.scene.lensFlareSystems;
  87046. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  87047. var lensFlareSystem = lensFlareSystems_1[_i];
  87048. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  87049. }
  87050. };
  87051. /**
  87052. * Disposes the component and the associated ressources.
  87053. */
  87054. LensFlareSystemSceneComponent.prototype.dispose = function () {
  87055. var lensFlareSystems = this.scene.lensFlareSystems;
  87056. while (lensFlareSystems.length) {
  87057. lensFlareSystems[0].dispose();
  87058. }
  87059. };
  87060. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  87061. // Lens flares
  87062. if (this.scene.lensFlaresEnabled) {
  87063. var lensFlareSystems = this.scene.lensFlareSystems;
  87064. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87065. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  87066. var lensFlareSystem = lensFlareSystems_2[_i];
  87067. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  87068. lensFlareSystem.render();
  87069. }
  87070. }
  87071. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87072. }
  87073. };
  87074. return LensFlareSystemSceneComponent;
  87075. }());
  87076. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  87077. })(BABYLON || (BABYLON = {}));
  87078. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  87079. var BABYLON;
  87080. (function (BABYLON) {
  87081. var LensFlareSystem = /** @class */ (function () {
  87082. function LensFlareSystem(name, emitter, scene) {
  87083. this.name = name;
  87084. this.lensFlares = new Array();
  87085. this.borderLimit = 300;
  87086. this.viewportBorder = 0;
  87087. this.layerMask = 0x0FFFFFFF;
  87088. this._vertexBuffers = {};
  87089. this._isEnabled = true;
  87090. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87091. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  87092. if (!component) {
  87093. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  87094. scene._addComponent(component);
  87095. }
  87096. this._emitter = emitter;
  87097. this.id = name;
  87098. scene.lensFlareSystems.push(this);
  87099. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  87100. var engine = scene.getEngine();
  87101. // VBO
  87102. var vertices = [];
  87103. vertices.push(1, 1);
  87104. vertices.push(-1, 1);
  87105. vertices.push(-1, -1);
  87106. vertices.push(1, -1);
  87107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87108. // Indices
  87109. var indices = [];
  87110. indices.push(0);
  87111. indices.push(1);
  87112. indices.push(2);
  87113. indices.push(0);
  87114. indices.push(2);
  87115. indices.push(3);
  87116. this._indexBuffer = engine.createIndexBuffer(indices);
  87117. // Effects
  87118. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  87119. }
  87120. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  87121. get: function () {
  87122. return this._isEnabled;
  87123. },
  87124. set: function (value) {
  87125. this._isEnabled = value;
  87126. },
  87127. enumerable: true,
  87128. configurable: true
  87129. });
  87130. LensFlareSystem.prototype.getScene = function () {
  87131. return this._scene;
  87132. };
  87133. LensFlareSystem.prototype.getEmitter = function () {
  87134. return this._emitter;
  87135. };
  87136. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  87137. this._emitter = newEmitter;
  87138. };
  87139. LensFlareSystem.prototype.getEmitterPosition = function () {
  87140. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  87141. };
  87142. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  87143. var position = this.getEmitterPosition();
  87144. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  87145. this._positionX = position.x;
  87146. this._positionY = position.y;
  87147. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  87148. if (this.viewportBorder > 0) {
  87149. globalViewport.x -= this.viewportBorder;
  87150. globalViewport.y -= this.viewportBorder;
  87151. globalViewport.width += this.viewportBorder * 2;
  87152. globalViewport.height += this.viewportBorder * 2;
  87153. position.x += this.viewportBorder;
  87154. position.y += this.viewportBorder;
  87155. this._positionX += this.viewportBorder;
  87156. this._positionY += this.viewportBorder;
  87157. }
  87158. if (position.z > 0) {
  87159. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  87160. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  87161. return true;
  87162. }
  87163. return true;
  87164. }
  87165. return false;
  87166. };
  87167. /** @hidden */
  87168. LensFlareSystem.prototype._isVisible = function () {
  87169. if (!this._isEnabled || !this._scene.activeCamera) {
  87170. return false;
  87171. }
  87172. var emitterPosition = this.getEmitterPosition();
  87173. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  87174. var distance = direction.length();
  87175. direction.normalize();
  87176. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  87177. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  87178. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  87179. };
  87180. LensFlareSystem.prototype.render = function () {
  87181. if (!this._effect.isReady() || !this._scene.activeCamera)
  87182. return false;
  87183. var engine = this._scene.getEngine();
  87184. var viewport = this._scene.activeCamera.viewport;
  87185. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  87186. // Position
  87187. if (!this.computeEffectivePosition(globalViewport)) {
  87188. return false;
  87189. }
  87190. // Visibility
  87191. if (!this._isVisible()) {
  87192. return false;
  87193. }
  87194. // Intensity
  87195. var awayX;
  87196. var awayY;
  87197. if (this._positionX < this.borderLimit + globalViewport.x) {
  87198. awayX = this.borderLimit + globalViewport.x - this._positionX;
  87199. }
  87200. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  87201. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  87202. }
  87203. else {
  87204. awayX = 0;
  87205. }
  87206. if (this._positionY < this.borderLimit + globalViewport.y) {
  87207. awayY = this.borderLimit + globalViewport.y - this._positionY;
  87208. }
  87209. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  87210. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  87211. }
  87212. else {
  87213. awayY = 0;
  87214. }
  87215. var away = (awayX > awayY) ? awayX : awayY;
  87216. away -= this.viewportBorder;
  87217. if (away > this.borderLimit) {
  87218. away = this.borderLimit;
  87219. }
  87220. var intensity = 1.0 - (away / this.borderLimit);
  87221. if (intensity < 0) {
  87222. return false;
  87223. }
  87224. if (intensity > 1.0) {
  87225. intensity = 1.0;
  87226. }
  87227. if (this.viewportBorder > 0) {
  87228. globalViewport.x += this.viewportBorder;
  87229. globalViewport.y += this.viewportBorder;
  87230. globalViewport.width -= this.viewportBorder * 2;
  87231. globalViewport.height -= this.viewportBorder * 2;
  87232. this._positionX -= this.viewportBorder;
  87233. this._positionY -= this.viewportBorder;
  87234. }
  87235. // Position
  87236. var centerX = globalViewport.x + globalViewport.width / 2;
  87237. var centerY = globalViewport.y + globalViewport.height / 2;
  87238. var distX = centerX - this._positionX;
  87239. var distY = centerY - this._positionY;
  87240. // Effects
  87241. engine.enableEffect(this._effect);
  87242. engine.setState(false);
  87243. engine.setDepthBuffer(false);
  87244. // VBOs
  87245. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  87246. // Flares
  87247. for (var index = 0; index < this.lensFlares.length; index++) {
  87248. var flare = this.lensFlares[index];
  87249. engine.setAlphaMode(flare.alphaMode);
  87250. var x = centerX - (distX * flare.position);
  87251. var y = centerY - (distY * flare.position);
  87252. var cw = flare.size;
  87253. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  87254. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  87255. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  87256. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  87257. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  87258. // Texture
  87259. this._effect.setTexture("textureSampler", flare.texture);
  87260. // Color
  87261. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  87262. // Draw order
  87263. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87264. }
  87265. engine.setDepthBuffer(true);
  87266. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87267. return true;
  87268. };
  87269. LensFlareSystem.prototype.dispose = function () {
  87270. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87271. if (vertexBuffer) {
  87272. vertexBuffer.dispose();
  87273. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87274. }
  87275. if (this._indexBuffer) {
  87276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87277. this._indexBuffer = null;
  87278. }
  87279. while (this.lensFlares.length) {
  87280. this.lensFlares[0].dispose();
  87281. }
  87282. // Remove from scene
  87283. var index = this._scene.lensFlareSystems.indexOf(this);
  87284. this._scene.lensFlareSystems.splice(index, 1);
  87285. };
  87286. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  87287. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  87288. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  87289. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  87290. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  87291. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  87292. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  87293. var parsedFlare = parsedLensFlareSystem.flares[index];
  87294. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  87295. }
  87296. return lensFlareSystem;
  87297. };
  87298. LensFlareSystem.prototype.serialize = function () {
  87299. var serializationObject = {};
  87300. serializationObject.id = this.id;
  87301. serializationObject.name = this.name;
  87302. serializationObject.emitterId = this.getEmitter().id;
  87303. serializationObject.borderLimit = this.borderLimit;
  87304. serializationObject.flares = [];
  87305. for (var index = 0; index < this.lensFlares.length; index++) {
  87306. var flare = this.lensFlares[index];
  87307. serializationObject.flares.push({
  87308. size: flare.size,
  87309. position: flare.position,
  87310. color: flare.color.asArray(),
  87311. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  87312. });
  87313. }
  87314. return serializationObject;
  87315. };
  87316. return LensFlareSystem;
  87317. }());
  87318. BABYLON.LensFlareSystem = LensFlareSystem;
  87319. })(BABYLON || (BABYLON = {}));
  87320. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  87321. var BABYLON;
  87322. (function (BABYLON) {
  87323. /**
  87324. * This is a holder class for the physics joint created by the physics plugin.
  87325. * It holds a set of functions to control the underlying joint.
  87326. */
  87327. var PhysicsJoint = /** @class */ (function () {
  87328. function PhysicsJoint(type, jointData) {
  87329. this.type = type;
  87330. this.jointData = jointData;
  87331. jointData.nativeParams = jointData.nativeParams || {};
  87332. }
  87333. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  87334. get: function () {
  87335. return this._physicsJoint;
  87336. },
  87337. set: function (newJoint) {
  87338. if (this._physicsJoint) {
  87339. //remove from the wolrd
  87340. }
  87341. this._physicsJoint = newJoint;
  87342. },
  87343. enumerable: true,
  87344. configurable: true
  87345. });
  87346. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  87347. set: function (physicsPlugin) {
  87348. this._physicsPlugin = physicsPlugin;
  87349. },
  87350. enumerable: true,
  87351. configurable: true
  87352. });
  87353. /**
  87354. * Execute a function that is physics-plugin specific.
  87355. * @param {Function} func the function that will be executed.
  87356. * It accepts two parameters: the physics world and the physics joint.
  87357. */
  87358. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  87359. func(this._physicsPlugin.world, this._physicsJoint);
  87360. };
  87361. //TODO check if the native joints are the same
  87362. //Joint Types
  87363. PhysicsJoint.DistanceJoint = 0;
  87364. PhysicsJoint.HingeJoint = 1;
  87365. PhysicsJoint.BallAndSocketJoint = 2;
  87366. PhysicsJoint.WheelJoint = 3;
  87367. PhysicsJoint.SliderJoint = 4;
  87368. //OIMO
  87369. PhysicsJoint.PrismaticJoint = 5;
  87370. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  87371. PhysicsJoint.UniversalJoint = 6;
  87372. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  87373. //Cannon
  87374. //Similar to a Ball-Joint. Different in params
  87375. PhysicsJoint.PointToPointJoint = 8;
  87376. //Cannon only at the moment
  87377. PhysicsJoint.SpringJoint = 9;
  87378. PhysicsJoint.LockJoint = 10;
  87379. return PhysicsJoint;
  87380. }());
  87381. BABYLON.PhysicsJoint = PhysicsJoint;
  87382. /**
  87383. * A class representing a physics distance joint.
  87384. */
  87385. var DistanceJoint = /** @class */ (function (_super) {
  87386. __extends(DistanceJoint, _super);
  87387. function DistanceJoint(jointData) {
  87388. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  87389. }
  87390. /**
  87391. * Update the predefined distance.
  87392. */
  87393. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  87394. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  87395. };
  87396. return DistanceJoint;
  87397. }(PhysicsJoint));
  87398. BABYLON.DistanceJoint = DistanceJoint;
  87399. var MotorEnabledJoint = /** @class */ (function (_super) {
  87400. __extends(MotorEnabledJoint, _super);
  87401. function MotorEnabledJoint(type, jointData) {
  87402. return _super.call(this, type, jointData) || this;
  87403. }
  87404. /**
  87405. * Set the motor values.
  87406. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87407. * @param {number} force the force to apply
  87408. * @param {number} maxForce max force for this motor.
  87409. */
  87410. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  87411. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  87412. };
  87413. /**
  87414. * Set the motor's limits.
  87415. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87416. */
  87417. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  87418. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  87419. };
  87420. return MotorEnabledJoint;
  87421. }(PhysicsJoint));
  87422. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  87423. /**
  87424. * This class represents a single hinge physics joint
  87425. */
  87426. var HingeJoint = /** @class */ (function (_super) {
  87427. __extends(HingeJoint, _super);
  87428. function HingeJoint(jointData) {
  87429. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  87430. }
  87431. /**
  87432. * Set the motor values.
  87433. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87434. * @param {number} force the force to apply
  87435. * @param {number} maxForce max force for this motor.
  87436. */
  87437. HingeJoint.prototype.setMotor = function (force, maxForce) {
  87438. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  87439. };
  87440. /**
  87441. * Set the motor's limits.
  87442. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87443. */
  87444. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  87445. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  87446. };
  87447. return HingeJoint;
  87448. }(MotorEnabledJoint));
  87449. BABYLON.HingeJoint = HingeJoint;
  87450. /**
  87451. * This class represents a dual hinge physics joint (same as wheel joint)
  87452. */
  87453. var Hinge2Joint = /** @class */ (function (_super) {
  87454. __extends(Hinge2Joint, _super);
  87455. function Hinge2Joint(jointData) {
  87456. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  87457. }
  87458. /**
  87459. * Set the motor values.
  87460. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87461. * @param {number} force the force to apply
  87462. * @param {number} maxForce max force for this motor.
  87463. * @param {motorIndex} the motor's index, 0 or 1.
  87464. */
  87465. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  87466. if (motorIndex === void 0) { motorIndex = 0; }
  87467. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  87468. };
  87469. /**
  87470. * Set the motor limits.
  87471. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87472. * @param {number} upperLimit the upper limit
  87473. * @param {number} lowerLimit lower limit
  87474. * @param {motorIndex} the motor's index, 0 or 1.
  87475. */
  87476. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  87477. if (motorIndex === void 0) { motorIndex = 0; }
  87478. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  87479. };
  87480. return Hinge2Joint;
  87481. }(MotorEnabledJoint));
  87482. BABYLON.Hinge2Joint = Hinge2Joint;
  87483. })(BABYLON || (BABYLON = {}));
  87484. //# sourceMappingURL=babylon.physicsJoint.js.map
  87485. var BABYLON;
  87486. (function (BABYLON) {
  87487. var PhysicsImpostor = /** @class */ (function () {
  87488. function PhysicsImpostor(object, type, _options, _scene) {
  87489. if (_options === void 0) { _options = { mass: 0 }; }
  87490. var _this = this;
  87491. this.object = object;
  87492. this.type = type;
  87493. this._options = _options;
  87494. this._scene = _scene;
  87495. this._bodyUpdateRequired = false;
  87496. this._onBeforePhysicsStepCallbacks = new Array();
  87497. this._onAfterPhysicsStepCallbacks = new Array();
  87498. this._onPhysicsCollideCallbacks = [];
  87499. this._deltaPosition = BABYLON.Vector3.Zero();
  87500. this._isDisposed = false;
  87501. //temp variables for parent rotation calculations
  87502. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  87503. this._tmpQuat = new BABYLON.Quaternion();
  87504. this._tmpQuat2 = new BABYLON.Quaternion();
  87505. /**
  87506. * this function is executed by the physics engine.
  87507. */
  87508. this.beforeStep = function () {
  87509. if (!_this._physicsEngine) {
  87510. return;
  87511. }
  87512. _this.object.translate(_this._deltaPosition, -1);
  87513. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  87514. _this.object.computeWorldMatrix(false);
  87515. if (_this.object.parent && _this.object.rotationQuaternion) {
  87516. _this.getParentsRotation();
  87517. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  87518. }
  87519. else {
  87520. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  87521. }
  87522. if (!_this._options.disableBidirectionalTransformation) {
  87523. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  87524. }
  87525. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  87526. func(_this);
  87527. });
  87528. };
  87529. /**
  87530. * this function is executed by the physics engine.
  87531. */
  87532. this.afterStep = function () {
  87533. if (!_this._physicsEngine) {
  87534. return;
  87535. }
  87536. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  87537. func(_this);
  87538. });
  87539. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  87540. // object has now its world rotation. needs to be converted to local.
  87541. if (_this.object.parent && _this.object.rotationQuaternion) {
  87542. _this.getParentsRotation();
  87543. _this._tmpQuat.conjugateInPlace();
  87544. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  87545. }
  87546. // take the position set and make it the absolute position of this object.
  87547. _this.object.setAbsolutePosition(_this.object.position);
  87548. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  87549. _this.object.translate(_this._deltaPosition, 1);
  87550. };
  87551. /**
  87552. * Legacy collision detection event support
  87553. */
  87554. this.onCollideEvent = null;
  87555. //event and body object due to cannon's event-based architecture.
  87556. this.onCollide = function (e) {
  87557. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  87558. return;
  87559. }
  87560. if (!_this._physicsEngine) {
  87561. return;
  87562. }
  87563. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  87564. if (otherImpostor) {
  87565. // Legacy collision detection event support
  87566. if (_this.onCollideEvent) {
  87567. _this.onCollideEvent(_this, otherImpostor);
  87568. }
  87569. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  87570. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  87571. }).forEach(function (obj) {
  87572. obj.callback(_this, otherImpostor);
  87573. });
  87574. }
  87575. };
  87576. //sanity check!
  87577. if (!this.object) {
  87578. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  87579. return;
  87580. }
  87581. //legacy support for old syntax.
  87582. if (!this._scene && object.getScene) {
  87583. this._scene = object.getScene();
  87584. }
  87585. if (!this._scene) {
  87586. return;
  87587. }
  87588. this._physicsEngine = this._scene.getPhysicsEngine();
  87589. if (!this._physicsEngine) {
  87590. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  87591. }
  87592. else {
  87593. //set the object's quaternion, if not set
  87594. if (!this.object.rotationQuaternion) {
  87595. if (this.object.rotation) {
  87596. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  87597. }
  87598. else {
  87599. this.object.rotationQuaternion = new BABYLON.Quaternion();
  87600. }
  87601. }
  87602. //default options params
  87603. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  87604. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  87605. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  87606. this._joints = [];
  87607. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  87608. if (!this.object.parent || this._options.ignoreParent) {
  87609. this._init();
  87610. }
  87611. else if (this.object.parent.physicsImpostor) {
  87612. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  87613. }
  87614. }
  87615. }
  87616. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  87617. get: function () {
  87618. return this._isDisposed;
  87619. },
  87620. enumerable: true,
  87621. configurable: true
  87622. });
  87623. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  87624. get: function () {
  87625. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  87626. },
  87627. set: function (value) {
  87628. this.setMass(value);
  87629. },
  87630. enumerable: true,
  87631. configurable: true
  87632. });
  87633. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  87634. get: function () {
  87635. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  87636. },
  87637. set: function (value) {
  87638. if (!this._physicsEngine) {
  87639. return;
  87640. }
  87641. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  87642. },
  87643. enumerable: true,
  87644. configurable: true
  87645. });
  87646. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  87647. get: function () {
  87648. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  87649. },
  87650. set: function (value) {
  87651. if (!this._physicsEngine) {
  87652. return;
  87653. }
  87654. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  87655. },
  87656. enumerable: true,
  87657. configurable: true
  87658. });
  87659. /**
  87660. * This function will completly initialize this impostor.
  87661. * It will create a new body - but only if this mesh has no parent.
  87662. * If it has, this impostor will not be used other than to define the impostor
  87663. * of the child mesh.
  87664. * @hidden
  87665. */
  87666. PhysicsImpostor.prototype._init = function () {
  87667. if (!this._physicsEngine) {
  87668. return;
  87669. }
  87670. this._physicsEngine.removeImpostor(this);
  87671. this.physicsBody = null;
  87672. this._parent = this._parent || this._getPhysicsParent();
  87673. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  87674. this._physicsEngine.addImpostor(this);
  87675. }
  87676. };
  87677. PhysicsImpostor.prototype._getPhysicsParent = function () {
  87678. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  87679. var parentMesh = this.object.parent;
  87680. return parentMesh.physicsImpostor;
  87681. }
  87682. return null;
  87683. };
  87684. /**
  87685. * Should a new body be generated.
  87686. */
  87687. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  87688. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87689. };
  87690. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87691. this.forceUpdate();
  87692. };
  87693. /**
  87694. * Force a regeneration of this or the parent's impostor's body.
  87695. * Use under cautious - This will remove all joints already implemented.
  87696. */
  87697. PhysicsImpostor.prototype.forceUpdate = function () {
  87698. this._init();
  87699. if (this.parent && !this._options.ignoreParent) {
  87700. this.parent.forceUpdate();
  87701. }
  87702. };
  87703. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87704. /*public get mesh(): AbstractMesh {
  87705. return this._mesh;
  87706. }*/
  87707. /**
  87708. * Gets the body that holds this impostor. Either its own, or its parent.
  87709. */
  87710. get: function () {
  87711. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87712. },
  87713. /**
  87714. * Set the physics body. Used mainly by the physics engine/plugin
  87715. */
  87716. set: function (physicsBody) {
  87717. if (this._physicsBody && this._physicsEngine) {
  87718. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87719. }
  87720. this._physicsBody = physicsBody;
  87721. this.resetUpdateFlags();
  87722. },
  87723. enumerable: true,
  87724. configurable: true
  87725. });
  87726. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87727. get: function () {
  87728. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87729. },
  87730. set: function (value) {
  87731. this._parent = value;
  87732. },
  87733. enumerable: true,
  87734. configurable: true
  87735. });
  87736. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87737. this._bodyUpdateRequired = false;
  87738. };
  87739. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87740. if (this.object.getBoundingInfo) {
  87741. var q = this.object.rotationQuaternion;
  87742. //reset rotation
  87743. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87744. //calculate the world matrix with no rotation
  87745. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87746. var boundingInfo = this.object.getBoundingInfo();
  87747. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87748. //bring back the rotation
  87749. this.object.rotationQuaternion = q;
  87750. //calculate the world matrix with the new rotation
  87751. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87752. return size;
  87753. }
  87754. else {
  87755. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87756. }
  87757. };
  87758. PhysicsImpostor.prototype.getObjectCenter = function () {
  87759. if (this.object.getBoundingInfo) {
  87760. var boundingInfo = this.object.getBoundingInfo();
  87761. return boundingInfo.boundingBox.centerWorld;
  87762. }
  87763. else {
  87764. return this.object.position;
  87765. }
  87766. };
  87767. /**
  87768. * Get a specific parametes from the options parameter.
  87769. */
  87770. PhysicsImpostor.prototype.getParam = function (paramName) {
  87771. return this._options[paramName];
  87772. };
  87773. /**
  87774. * Sets a specific parameter in the options given to the physics plugin
  87775. */
  87776. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87777. this._options[paramName] = value;
  87778. this._bodyUpdateRequired = true;
  87779. };
  87780. /**
  87781. * Specifically change the body's mass option. Won't recreate the physics body object
  87782. */
  87783. PhysicsImpostor.prototype.setMass = function (mass) {
  87784. if (this.getParam("mass") !== mass) {
  87785. this.setParam("mass", mass);
  87786. }
  87787. if (this._physicsEngine) {
  87788. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  87789. }
  87790. };
  87791. PhysicsImpostor.prototype.getLinearVelocity = function () {
  87792. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  87793. };
  87794. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  87795. if (this._physicsEngine) {
  87796. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  87797. }
  87798. };
  87799. PhysicsImpostor.prototype.getAngularVelocity = function () {
  87800. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  87801. };
  87802. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  87803. if (this._physicsEngine) {
  87804. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  87805. }
  87806. };
  87807. /**
  87808. * Execute a function with the physics plugin native code.
  87809. * Provide a function the will have two variables - the world object and the physics body object.
  87810. */
  87811. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  87812. if (this._physicsEngine) {
  87813. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  87814. }
  87815. };
  87816. /**
  87817. * Register a function that will be executed before the physics world is stepping forward.
  87818. */
  87819. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  87820. this._onBeforePhysicsStepCallbacks.push(func);
  87821. };
  87822. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  87823. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  87824. if (index > -1) {
  87825. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  87826. }
  87827. else {
  87828. BABYLON.Tools.Warn("Function to remove was not found");
  87829. }
  87830. };
  87831. /**
  87832. * Register a function that will be executed after the physics step
  87833. */
  87834. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  87835. this._onAfterPhysicsStepCallbacks.push(func);
  87836. };
  87837. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  87838. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  87839. if (index > -1) {
  87840. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  87841. }
  87842. else {
  87843. BABYLON.Tools.Warn("Function to remove was not found");
  87844. }
  87845. };
  87846. /**
  87847. * register a function that will be executed when this impostor collides against a different body.
  87848. */
  87849. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  87850. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87851. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  87852. };
  87853. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  87854. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87855. var index = -1;
  87856. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  87857. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  87858. // chcek the arrays match
  87859. var sameList = cbDef.otherImpostors.every(function (impostor) {
  87860. return collidedAgainstList.indexOf(impostor) > -1;
  87861. });
  87862. if (sameList) {
  87863. index = idx;
  87864. }
  87865. return sameList;
  87866. }
  87867. return false;
  87868. });
  87869. if (found) {
  87870. this._onPhysicsCollideCallbacks.splice(index, 1);
  87871. }
  87872. else {
  87873. BABYLON.Tools.Warn("Function to remove was not found");
  87874. }
  87875. };
  87876. PhysicsImpostor.prototype.getParentsRotation = function () {
  87877. var parent = this.object.parent;
  87878. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  87879. while (parent) {
  87880. if (parent.rotationQuaternion) {
  87881. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  87882. }
  87883. else {
  87884. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  87885. }
  87886. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  87887. parent = parent.parent;
  87888. }
  87889. return this._tmpQuat;
  87890. };
  87891. /**
  87892. * Apply a force
  87893. */
  87894. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  87895. if (this._physicsEngine) {
  87896. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  87897. }
  87898. return this;
  87899. };
  87900. /**
  87901. * Apply an impulse
  87902. */
  87903. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  87904. if (this._physicsEngine) {
  87905. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  87906. }
  87907. return this;
  87908. };
  87909. /**
  87910. * A help function to create a joint.
  87911. */
  87912. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  87913. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  87914. this.addJoint(otherImpostor, joint);
  87915. return this;
  87916. };
  87917. /**
  87918. * Add a joint to this impostor with a different impostor.
  87919. */
  87920. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87921. this._joints.push({
  87922. otherImpostor: otherImpostor,
  87923. joint: joint
  87924. });
  87925. if (this._physicsEngine) {
  87926. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87927. }
  87928. return this;
  87929. };
  87930. /**
  87931. * Will keep this body still, in a sleep mode.
  87932. */
  87933. PhysicsImpostor.prototype.sleep = function () {
  87934. if (this._physicsEngine) {
  87935. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87936. }
  87937. return this;
  87938. };
  87939. /**
  87940. * Wake the body up.
  87941. */
  87942. PhysicsImpostor.prototype.wakeUp = function () {
  87943. if (this._physicsEngine) {
  87944. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87945. }
  87946. return this;
  87947. };
  87948. PhysicsImpostor.prototype.clone = function (newObject) {
  87949. if (!newObject)
  87950. return null;
  87951. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87952. };
  87953. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87954. var _this = this;
  87955. //no dispose if no physics engine is available.
  87956. if (!this._physicsEngine) {
  87957. return;
  87958. }
  87959. this._joints.forEach(function (j) {
  87960. if (_this._physicsEngine) {
  87961. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87962. }
  87963. });
  87964. //dispose the physics body
  87965. this._physicsEngine.removeImpostor(this);
  87966. if (this.parent) {
  87967. this.parent.forceUpdate();
  87968. }
  87969. else {
  87970. /*this._object.getChildMeshes().forEach(function(mesh) {
  87971. if (mesh.physicsImpostor) {
  87972. if (disposeChildren) {
  87973. mesh.physicsImpostor.dispose();
  87974. mesh.physicsImpostor = null;
  87975. }
  87976. }
  87977. })*/
  87978. }
  87979. this._isDisposed = true;
  87980. };
  87981. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87982. this._deltaPosition.copyFrom(position);
  87983. };
  87984. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87985. if (!this._deltaRotation) {
  87986. this._deltaRotation = new BABYLON.Quaternion();
  87987. }
  87988. this._deltaRotation.copyFrom(rotation);
  87989. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87990. };
  87991. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87992. if (this._physicsEngine) {
  87993. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87994. }
  87995. return this;
  87996. };
  87997. PhysicsImpostor.prototype.getRadius = function () {
  87998. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87999. };
  88000. /**
  88001. * Sync a bone with this impostor
  88002. * @param bone The bone to sync to the impostor.
  88003. * @param boneMesh The mesh that the bone is influencing.
  88004. * @param jointPivot The pivot of the joint / bone in local space.
  88005. * @param distToJoint Optional distance from the impostor to the joint.
  88006. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88007. */
  88008. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  88009. var tempVec = PhysicsImpostor._tmpVecs[0];
  88010. var mesh = this.object;
  88011. if (mesh.rotationQuaternion) {
  88012. if (adjustRotation) {
  88013. var tempQuat = PhysicsImpostor._tmpQuat;
  88014. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  88015. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  88016. }
  88017. else {
  88018. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  88019. }
  88020. }
  88021. tempVec.x = 0;
  88022. tempVec.y = 0;
  88023. tempVec.z = 0;
  88024. if (jointPivot) {
  88025. tempVec.x = jointPivot.x;
  88026. tempVec.y = jointPivot.y;
  88027. tempVec.z = jointPivot.z;
  88028. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  88029. if (distToJoint === undefined || distToJoint === null) {
  88030. distToJoint = jointPivot.length();
  88031. }
  88032. tempVec.x *= distToJoint;
  88033. tempVec.y *= distToJoint;
  88034. tempVec.z *= distToJoint;
  88035. }
  88036. if (bone.getParent()) {
  88037. tempVec.addInPlace(mesh.getAbsolutePosition());
  88038. bone.setAbsolutePosition(tempVec, boneMesh);
  88039. }
  88040. else {
  88041. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  88042. boneMesh.position.x -= tempVec.x;
  88043. boneMesh.position.y -= tempVec.y;
  88044. boneMesh.position.z -= tempVec.z;
  88045. }
  88046. };
  88047. /**
  88048. * Sync impostor to a bone
  88049. * @param bone The bone that the impostor will be synced to.
  88050. * @param boneMesh The mesh that the bone is influencing.
  88051. * @param jointPivot The pivot of the joint / bone in local space.
  88052. * @param distToJoint Optional distance from the impostor to the joint.
  88053. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88054. * @param boneAxis Optional vector3 axis the bone is aligned with
  88055. */
  88056. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  88057. var mesh = this.object;
  88058. if (mesh.rotationQuaternion) {
  88059. if (adjustRotation) {
  88060. var tempQuat = PhysicsImpostor._tmpQuat;
  88061. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  88062. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  88063. }
  88064. else {
  88065. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  88066. }
  88067. }
  88068. var pos = PhysicsImpostor._tmpVecs[0];
  88069. var boneDir = PhysicsImpostor._tmpVecs[1];
  88070. if (!boneAxis) {
  88071. boneAxis = PhysicsImpostor._tmpVecs[2];
  88072. boneAxis.x = 0;
  88073. boneAxis.y = 1;
  88074. boneAxis.z = 0;
  88075. }
  88076. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  88077. bone.getAbsolutePositionToRef(boneMesh, pos);
  88078. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  88079. distToJoint = jointPivot.length();
  88080. }
  88081. if (distToJoint !== undefined && distToJoint !== null) {
  88082. pos.x += boneDir.x * distToJoint;
  88083. pos.y += boneDir.y * distToJoint;
  88084. pos.z += boneDir.z * distToJoint;
  88085. }
  88086. mesh.setAbsolutePosition(pos);
  88087. };
  88088. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  88089. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  88090. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88091. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  88092. //Impostor types
  88093. PhysicsImpostor.NoImpostor = 0;
  88094. PhysicsImpostor.SphereImpostor = 1;
  88095. PhysicsImpostor.BoxImpostor = 2;
  88096. PhysicsImpostor.PlaneImpostor = 3;
  88097. PhysicsImpostor.MeshImpostor = 4;
  88098. PhysicsImpostor.CylinderImpostor = 7;
  88099. PhysicsImpostor.ParticleImpostor = 8;
  88100. PhysicsImpostor.HeightmapImpostor = 9;
  88101. return PhysicsImpostor;
  88102. }());
  88103. BABYLON.PhysicsImpostor = PhysicsImpostor;
  88104. })(BABYLON || (BABYLON = {}));
  88105. //# sourceMappingURL=babylon.physicsImpostor.js.map
  88106. var BABYLON;
  88107. (function (BABYLON) {
  88108. var PhysicsEngine = /** @class */ (function () {
  88109. function PhysicsEngine(gravity, _physicsPlugin) {
  88110. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  88111. this._physicsPlugin = _physicsPlugin;
  88112. //new methods and parameters
  88113. this._impostors = [];
  88114. this._joints = [];
  88115. if (!this._physicsPlugin.isSupported()) {
  88116. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  88117. + "Please make sure it is included.");
  88118. }
  88119. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  88120. this.setGravity(gravity);
  88121. this.setTimeStep();
  88122. }
  88123. PhysicsEngine.prototype.setGravity = function (gravity) {
  88124. this.gravity = gravity;
  88125. this._physicsPlugin.setGravity(this.gravity);
  88126. };
  88127. /**
  88128. * Set the time step of the physics engine.
  88129. * default is 1/60.
  88130. * To slow it down, enter 1/600 for example.
  88131. * To speed it up, 1/30
  88132. * @param {number} newTimeStep the new timestep to apply to this world.
  88133. */
  88134. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  88135. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  88136. this._physicsPlugin.setTimeStep(newTimeStep);
  88137. };
  88138. /**
  88139. * Get the time step of the physics engine.
  88140. */
  88141. PhysicsEngine.prototype.getTimeStep = function () {
  88142. return this._physicsPlugin.getTimeStep();
  88143. };
  88144. PhysicsEngine.prototype.dispose = function () {
  88145. this._impostors.forEach(function (impostor) {
  88146. impostor.dispose();
  88147. });
  88148. this._physicsPlugin.dispose();
  88149. };
  88150. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  88151. return this._physicsPlugin.name;
  88152. };
  88153. /**
  88154. * Adding a new impostor for the impostor tracking.
  88155. * This will be done by the impostor itself.
  88156. * @param {PhysicsImpostor} impostor the impostor to add
  88157. */
  88158. PhysicsEngine.prototype.addImpostor = function (impostor) {
  88159. impostor.uniqueId = this._impostors.push(impostor);
  88160. //if no parent, generate the body
  88161. if (!impostor.parent) {
  88162. this._physicsPlugin.generatePhysicsBody(impostor);
  88163. }
  88164. };
  88165. /**
  88166. * Remove an impostor from the engine.
  88167. * This impostor and its mesh will not longer be updated by the physics engine.
  88168. * @param {PhysicsImpostor} impostor the impostor to remove
  88169. */
  88170. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  88171. var index = this._impostors.indexOf(impostor);
  88172. if (index > -1) {
  88173. var removed = this._impostors.splice(index, 1);
  88174. //Is it needed?
  88175. if (removed.length) {
  88176. //this will also remove it from the world.
  88177. removed[0].physicsBody = null;
  88178. }
  88179. }
  88180. };
  88181. /**
  88182. * Add a joint to the physics engine
  88183. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  88184. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  88185. * @param {PhysicsJoint} the joint that will connect both impostors.
  88186. */
  88187. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  88188. var impostorJoint = {
  88189. mainImpostor: mainImpostor,
  88190. connectedImpostor: connectedImpostor,
  88191. joint: joint
  88192. };
  88193. joint.physicsPlugin = this._physicsPlugin;
  88194. this._joints.push(impostorJoint);
  88195. this._physicsPlugin.generateJoint(impostorJoint);
  88196. };
  88197. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  88198. var matchingJoints = this._joints.filter(function (impostorJoint) {
  88199. return (impostorJoint.connectedImpostor === connectedImpostor
  88200. && impostorJoint.joint === joint
  88201. && impostorJoint.mainImpostor === mainImpostor);
  88202. });
  88203. if (matchingJoints.length) {
  88204. this._physicsPlugin.removeJoint(matchingJoints[0]);
  88205. //TODO remove it from the list as well
  88206. }
  88207. };
  88208. /**
  88209. * Called by the scene. no need to call it.
  88210. * @hidden
  88211. */
  88212. PhysicsEngine.prototype._step = function (delta) {
  88213. var _this = this;
  88214. //check if any mesh has no body / requires an update
  88215. this._impostors.forEach(function (impostor) {
  88216. if (impostor.isBodyInitRequired()) {
  88217. _this._physicsPlugin.generatePhysicsBody(impostor);
  88218. }
  88219. });
  88220. if (delta > 0.1) {
  88221. delta = 0.1;
  88222. }
  88223. else if (delta <= 0) {
  88224. delta = 1.0 / 60.0;
  88225. }
  88226. this._physicsPlugin.executeStep(delta, this._impostors);
  88227. };
  88228. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  88229. return this._physicsPlugin;
  88230. };
  88231. PhysicsEngine.prototype.getImpostors = function () {
  88232. return this._impostors;
  88233. };
  88234. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  88235. for (var i = 0; i < this._impostors.length; ++i) {
  88236. if (this._impostors[i].object === object) {
  88237. return this._impostors[i];
  88238. }
  88239. }
  88240. return null;
  88241. };
  88242. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  88243. for (var i = 0; i < this._impostors.length; ++i) {
  88244. if (this._impostors[i].physicsBody === body) {
  88245. return this._impostors[i];
  88246. }
  88247. }
  88248. return null;
  88249. };
  88250. // Statics
  88251. PhysicsEngine.Epsilon = 0.001;
  88252. return PhysicsEngine;
  88253. }());
  88254. BABYLON.PhysicsEngine = PhysicsEngine;
  88255. })(BABYLON || (BABYLON = {}));
  88256. //# sourceMappingURL=babylon.physicsEngine.js.map
  88257. var BABYLON;
  88258. (function (BABYLON) {
  88259. var PhysicsHelper = /** @class */ (function () {
  88260. function PhysicsHelper(scene) {
  88261. this._scene = scene;
  88262. this._physicsEngine = this._scene.getPhysicsEngine();
  88263. if (!this._physicsEngine) {
  88264. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  88265. }
  88266. }
  88267. /**
  88268. * @param {Vector3} origin the origin of the explosion
  88269. * @param {number} radius the explosion radius
  88270. * @param {number} strength the explosion strength
  88271. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88272. */
  88273. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  88274. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88275. if (!this._physicsEngine) {
  88276. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  88277. return null;
  88278. }
  88279. var impostors = this._physicsEngine.getImpostors();
  88280. if (impostors.length === 0) {
  88281. return null;
  88282. }
  88283. var event = new PhysicsRadialExplosionEvent(this._scene);
  88284. impostors.forEach(function (impostor) {
  88285. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88286. if (!impostorForceAndContactPoint) {
  88287. return;
  88288. }
  88289. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88290. });
  88291. event.dispose(false);
  88292. return event;
  88293. };
  88294. /**
  88295. * @param {Vector3} origin the origin of the explosion
  88296. * @param {number} radius the explosion radius
  88297. * @param {number} strength the explosion strength
  88298. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88299. */
  88300. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  88301. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88302. if (!this._physicsEngine) {
  88303. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88304. return null;
  88305. }
  88306. var impostors = this._physicsEngine.getImpostors();
  88307. if (impostors.length === 0) {
  88308. return null;
  88309. }
  88310. var event = new PhysicsRadialExplosionEvent(this._scene);
  88311. impostors.forEach(function (impostor) {
  88312. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88313. if (!impostorForceAndContactPoint) {
  88314. return;
  88315. }
  88316. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88317. });
  88318. event.dispose(false);
  88319. return event;
  88320. };
  88321. /**
  88322. * @param {Vector3} origin the origin of the explosion
  88323. * @param {number} radius the explosion radius
  88324. * @param {number} strength the explosion strength
  88325. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88326. */
  88327. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  88328. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88329. if (!this._physicsEngine) {
  88330. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88331. return null;
  88332. }
  88333. var impostors = this._physicsEngine.getImpostors();
  88334. if (impostors.length === 0) {
  88335. return null;
  88336. }
  88337. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  88338. event.dispose(false);
  88339. return event;
  88340. };
  88341. /**
  88342. * @param {Vector3} origin the origin of the updraft
  88343. * @param {number} radius the radius of the updraft
  88344. * @param {number} strength the strength of the updraft
  88345. * @param {number} height the height of the updraft
  88346. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  88347. */
  88348. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  88349. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  88350. if (!this._physicsEngine) {
  88351. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88352. return null;
  88353. }
  88354. if (this._physicsEngine.getImpostors().length === 0) {
  88355. return null;
  88356. }
  88357. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  88358. event.dispose(false);
  88359. return event;
  88360. };
  88361. /**
  88362. * @param {Vector3} origin the of the vortex
  88363. * @param {number} radius the radius of the vortex
  88364. * @param {number} strength the strength of the vortex
  88365. * @param {number} height the height of the vortex
  88366. */
  88367. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  88368. if (!this._physicsEngine) {
  88369. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88370. return null;
  88371. }
  88372. if (this._physicsEngine.getImpostors().length === 0) {
  88373. return null;
  88374. }
  88375. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  88376. event.dispose(false);
  88377. return event;
  88378. };
  88379. return PhysicsHelper;
  88380. }());
  88381. BABYLON.PhysicsHelper = PhysicsHelper;
  88382. /***** Radial explosion *****/
  88383. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  88384. function PhysicsRadialExplosionEvent(scene) {
  88385. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  88386. this._rays = [];
  88387. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  88388. this._scene = scene;
  88389. }
  88390. /**
  88391. * Returns the data related to the radial explosion event (sphere & rays).
  88392. * @returns {PhysicsRadialExplosionEventData}
  88393. */
  88394. PhysicsRadialExplosionEvent.prototype.getData = function () {
  88395. this._dataFetched = true;
  88396. return {
  88397. sphere: this._sphere,
  88398. rays: this._rays,
  88399. };
  88400. };
  88401. /**
  88402. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  88403. * @param impostor
  88404. * @param {Vector3} origin the origin of the explosion
  88405. * @param {number} radius the explosion radius
  88406. * @param {number} strength the explosion strength
  88407. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  88408. * @returns {Nullable<PhysicsForceAndContactPoint>}
  88409. */
  88410. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  88411. if (impostor.mass === 0) {
  88412. return null;
  88413. }
  88414. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  88415. return null;
  88416. }
  88417. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88418. return null;
  88419. }
  88420. var impostorObjectCenter = impostor.getObjectCenter();
  88421. var direction = impostorObjectCenter.subtract(origin);
  88422. var ray = new BABYLON.Ray(origin, direction, radius);
  88423. this._rays.push(ray);
  88424. var hit = ray.intersectsMesh(impostor.object);
  88425. var contactPoint = hit.pickedPoint;
  88426. if (!contactPoint) {
  88427. return null;
  88428. }
  88429. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  88430. if (distanceFromOrigin > radius) {
  88431. return null;
  88432. }
  88433. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  88434. ? strength
  88435. : strength * (1 - (distanceFromOrigin / radius));
  88436. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88437. return { force: force, contactPoint: contactPoint };
  88438. };
  88439. /**
  88440. * Disposes the sphere.
  88441. * @param {bolean} force
  88442. */
  88443. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  88444. var _this = this;
  88445. if (force === void 0) { force = true; }
  88446. if (force) {
  88447. this._sphere.dispose();
  88448. }
  88449. else {
  88450. setTimeout(function () {
  88451. if (!_this._dataFetched) {
  88452. _this._sphere.dispose();
  88453. }
  88454. }, 0);
  88455. }
  88456. };
  88457. /*** Helpers ***/
  88458. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  88459. if (!this._sphere) {
  88460. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  88461. this._sphere.isVisible = false;
  88462. }
  88463. };
  88464. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  88465. var impostorObject = impostor.object;
  88466. this._prepareSphere();
  88467. this._sphere.position = origin;
  88468. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  88469. this._sphere._updateBoundingInfo();
  88470. this._sphere.computeWorldMatrix(true);
  88471. return this._sphere.intersectsMesh(impostorObject, true);
  88472. };
  88473. return PhysicsRadialExplosionEvent;
  88474. }());
  88475. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  88476. /***** Gravitational Field *****/
  88477. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  88478. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  88479. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88480. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88481. this._physicsHelper = physicsHelper;
  88482. this._scene = scene;
  88483. this._origin = origin;
  88484. this._radius = radius;
  88485. this._strength = strength;
  88486. this._falloff = falloff;
  88487. this._tickCallback = this._tick.bind(this);
  88488. }
  88489. /**
  88490. * Returns the data related to the gravitational field event (sphere).
  88491. * @returns {PhysicsGravitationalFieldEventData}
  88492. */
  88493. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  88494. this._dataFetched = true;
  88495. return {
  88496. sphere: this._sphere,
  88497. };
  88498. };
  88499. /**
  88500. * Enables the gravitational field.
  88501. */
  88502. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  88503. this._tickCallback.call(this);
  88504. this._scene.registerBeforeRender(this._tickCallback);
  88505. };
  88506. /**
  88507. * Disables the gravitational field.
  88508. */
  88509. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  88510. this._scene.unregisterBeforeRender(this._tickCallback);
  88511. };
  88512. /**
  88513. * Disposes the sphere.
  88514. * @param {bolean} force
  88515. */
  88516. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  88517. var _this = this;
  88518. if (force === void 0) { force = true; }
  88519. if (force) {
  88520. this._sphere.dispose();
  88521. }
  88522. else {
  88523. setTimeout(function () {
  88524. if (!_this._dataFetched) {
  88525. _this._sphere.dispose();
  88526. }
  88527. }, 0);
  88528. }
  88529. };
  88530. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  88531. // Since the params won't change, we fetch the event only once
  88532. if (this._sphere) {
  88533. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88534. }
  88535. else {
  88536. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88537. if (radialExplosionEvent) {
  88538. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  88539. }
  88540. }
  88541. };
  88542. return PhysicsGravitationalFieldEvent;
  88543. }());
  88544. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  88545. /***** Updraft *****/
  88546. var PhysicsUpdraftEvent = /** @class */ (function () {
  88547. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  88548. this._scene = _scene;
  88549. this._origin = _origin;
  88550. this._radius = _radius;
  88551. this._strength = _strength;
  88552. this._height = _height;
  88553. this._updraftMode = _updraftMode;
  88554. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88555. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  88556. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88557. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88558. this._physicsEngine = this._scene.getPhysicsEngine();
  88559. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88560. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88561. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88562. this._originDirection = this._origin.subtract(this._originTop).normalize();
  88563. }
  88564. this._tickCallback = this._tick.bind(this);
  88565. }
  88566. /**
  88567. * Returns the data related to the updraft event (cylinder).
  88568. * @returns {PhysicsUpdraftEventData}
  88569. */
  88570. PhysicsUpdraftEvent.prototype.getData = function () {
  88571. this._dataFetched = true;
  88572. return {
  88573. cylinder: this._cylinder,
  88574. };
  88575. };
  88576. /**
  88577. * Enables the updraft.
  88578. */
  88579. PhysicsUpdraftEvent.prototype.enable = function () {
  88580. this._tickCallback.call(this);
  88581. this._scene.registerBeforeRender(this._tickCallback);
  88582. };
  88583. /**
  88584. * Disables the cortex.
  88585. */
  88586. PhysicsUpdraftEvent.prototype.disable = function () {
  88587. this._scene.unregisterBeforeRender(this._tickCallback);
  88588. };
  88589. /**
  88590. * Disposes the sphere.
  88591. * @param {bolean} force
  88592. */
  88593. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  88594. var _this = this;
  88595. if (force === void 0) { force = true; }
  88596. if (force) {
  88597. this._cylinder.dispose();
  88598. }
  88599. else {
  88600. setTimeout(function () {
  88601. if (!_this._dataFetched) {
  88602. _this._cylinder.dispose();
  88603. }
  88604. }, 0);
  88605. }
  88606. };
  88607. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88608. if (impostor.mass === 0) {
  88609. return null;
  88610. }
  88611. if (!this._intersectsWithCylinder(impostor)) {
  88612. return null;
  88613. }
  88614. var impostorObjectCenter = impostor.getObjectCenter();
  88615. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88616. var direction = this._originDirection;
  88617. }
  88618. else {
  88619. var direction = impostorObjectCenter.subtract(this._originTop);
  88620. }
  88621. var multiplier = this._strength * -1;
  88622. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88623. return { force: force, contactPoint: impostorObjectCenter };
  88624. };
  88625. PhysicsUpdraftEvent.prototype._tick = function () {
  88626. var _this = this;
  88627. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88628. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88629. if (!impostorForceAndContactPoint) {
  88630. return;
  88631. }
  88632. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88633. });
  88634. };
  88635. /*** Helpers ***/
  88636. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  88637. if (!this._cylinder) {
  88638. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  88639. height: this._height,
  88640. diameter: this._radius * 2,
  88641. }, this._scene);
  88642. this._cylinder.isVisible = false;
  88643. }
  88644. };
  88645. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  88646. var impostorObject = impostor.object;
  88647. this._prepareCylinder();
  88648. this._cylinder.position = this._cylinderPosition;
  88649. return this._cylinder.intersectsMesh(impostorObject, true);
  88650. };
  88651. return PhysicsUpdraftEvent;
  88652. }());
  88653. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  88654. /***** Vortex *****/
  88655. var PhysicsVortexEvent = /** @class */ (function () {
  88656. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  88657. this._scene = _scene;
  88658. this._origin = _origin;
  88659. this._radius = _radius;
  88660. this._strength = _strength;
  88661. this._height = _height;
  88662. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88663. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  88664. this._updraftMultiplier = 0.02;
  88665. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88666. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88667. this._physicsEngine = this._scene.getPhysicsEngine();
  88668. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88669. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88670. this._tickCallback = this._tick.bind(this);
  88671. }
  88672. /**
  88673. * Returns the data related to the vortex event (cylinder).
  88674. * @returns {PhysicsVortexEventData}
  88675. */
  88676. PhysicsVortexEvent.prototype.getData = function () {
  88677. this._dataFetched = true;
  88678. return {
  88679. cylinder: this._cylinder,
  88680. };
  88681. };
  88682. /**
  88683. * Enables the vortex.
  88684. */
  88685. PhysicsVortexEvent.prototype.enable = function () {
  88686. this._tickCallback.call(this);
  88687. this._scene.registerBeforeRender(this._tickCallback);
  88688. };
  88689. /**
  88690. * Disables the cortex.
  88691. */
  88692. PhysicsVortexEvent.prototype.disable = function () {
  88693. this._scene.unregisterBeforeRender(this._tickCallback);
  88694. };
  88695. /**
  88696. * Disposes the sphere.
  88697. * @param {bolean} force
  88698. */
  88699. PhysicsVortexEvent.prototype.dispose = function (force) {
  88700. var _this = this;
  88701. if (force === void 0) { force = true; }
  88702. if (force) {
  88703. this._cylinder.dispose();
  88704. }
  88705. else {
  88706. setTimeout(function () {
  88707. if (!_this._dataFetched) {
  88708. _this._cylinder.dispose();
  88709. }
  88710. }, 0);
  88711. }
  88712. };
  88713. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88714. if (impostor.mass === 0) {
  88715. return null;
  88716. }
  88717. if (!this._intersectsWithCylinder(impostor)) {
  88718. return null;
  88719. }
  88720. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88721. return null;
  88722. }
  88723. var impostorObjectCenter = impostor.getObjectCenter();
  88724. 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)
  88725. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88726. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88727. var hit = ray.intersectsMesh(impostor.object);
  88728. var contactPoint = hit.pickedPoint;
  88729. if (!contactPoint) {
  88730. return null;
  88731. }
  88732. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88733. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88734. var directionToOrigin = contactPoint.normalize();
  88735. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88736. directionToOrigin = directionToOrigin.negate();
  88737. }
  88738. // TODO: find a more physically based solution
  88739. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88740. var forceX = directionToOrigin.x * this._strength / 8;
  88741. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88742. var forceZ = directionToOrigin.z * this._strength / 8;
  88743. }
  88744. else {
  88745. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88746. var forceY = this._originTop.y * this._updraftMultiplier;
  88747. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88748. }
  88749. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88750. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88751. return { force: force, contactPoint: impostorObjectCenter };
  88752. };
  88753. PhysicsVortexEvent.prototype._tick = function () {
  88754. var _this = this;
  88755. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88756. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88757. if (!impostorForceAndContactPoint) {
  88758. return;
  88759. }
  88760. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88761. });
  88762. };
  88763. /*** Helpers ***/
  88764. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88765. if (!this._cylinder) {
  88766. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88767. height: this._height,
  88768. diameter: this._radius * 2,
  88769. }, this._scene);
  88770. this._cylinder.isVisible = false;
  88771. }
  88772. };
  88773. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88774. var impostorObject = impostor.object;
  88775. this._prepareCylinder();
  88776. this._cylinder.position = this._cylinderPosition;
  88777. return this._cylinder.intersectsMesh(impostorObject, true);
  88778. };
  88779. return PhysicsVortexEvent;
  88780. }());
  88781. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  88782. /***** Enums *****/
  88783. /**
  88784. * The strenght of the force in correspondence to the distance of the affected object
  88785. */
  88786. var PhysicsRadialImpulseFalloff;
  88787. (function (PhysicsRadialImpulseFalloff) {
  88788. /** Defines that impulse is constant in strength across it's whole radius */
  88789. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  88790. /** DEfines that impulse gets weaker if it's further from the origin */
  88791. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  88792. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  88793. /**
  88794. * The strenght of the force in correspondence to the distance of the affected object
  88795. */
  88796. var PhysicsUpdraftMode;
  88797. (function (PhysicsUpdraftMode) {
  88798. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  88799. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  88800. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  88801. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  88802. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  88803. })(BABYLON || (BABYLON = {}));
  88804. //# sourceMappingURL=babylon.physicsHelper.js.map
  88805. var BABYLON;
  88806. (function (BABYLON) {
  88807. var CannonJSPlugin = /** @class */ (function () {
  88808. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  88809. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  88810. if (iterations === void 0) { iterations = 10; }
  88811. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  88812. this.name = "CannonJSPlugin";
  88813. this._physicsMaterials = new Array();
  88814. this._fixedTimeStep = 1 / 60;
  88815. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  88816. this.BJSCANNON = CANNON;
  88817. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  88818. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  88819. this._tmpPosition = BABYLON.Vector3.Zero();
  88820. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  88821. this._tmpUnityRotation = new BABYLON.Quaternion();
  88822. if (!this.isSupported()) {
  88823. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  88824. return;
  88825. }
  88826. this._extendNamespace();
  88827. this.world = new this.BJSCANNON.World();
  88828. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  88829. this.world.solver.iterations = iterations;
  88830. }
  88831. CannonJSPlugin.prototype.setGravity = function (gravity) {
  88832. this.world.gravity.copy(gravity);
  88833. };
  88834. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  88835. this._fixedTimeStep = timeStep;
  88836. };
  88837. CannonJSPlugin.prototype.getTimeStep = function () {
  88838. return this._fixedTimeStep;
  88839. };
  88840. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  88841. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  88842. };
  88843. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88844. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88845. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88846. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  88847. };
  88848. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88849. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88850. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88851. impostor.physicsBody.applyForce(impulse, worldPoint);
  88852. };
  88853. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88854. //parent-child relationship. Does this impostor has a parent impostor?
  88855. if (impostor.parent) {
  88856. if (impostor.physicsBody) {
  88857. this.removePhysicsBody(impostor);
  88858. //TODO is that needed?
  88859. impostor.forceUpdate();
  88860. }
  88861. return;
  88862. }
  88863. //should a new body be created for this impostor?
  88864. if (impostor.isBodyInitRequired()) {
  88865. var shape = this._createShape(impostor);
  88866. //unregister events, if body is being changed
  88867. var oldBody = impostor.physicsBody;
  88868. if (oldBody) {
  88869. this.removePhysicsBody(impostor);
  88870. }
  88871. //create the body and material
  88872. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  88873. var bodyCreationObject = {
  88874. mass: impostor.getParam("mass"),
  88875. material: material
  88876. };
  88877. // A simple extend, in case native options were used.
  88878. var nativeOptions = impostor.getParam("nativeOptions");
  88879. for (var key in nativeOptions) {
  88880. if (nativeOptions.hasOwnProperty(key)) {
  88881. bodyCreationObject[key] = nativeOptions[key];
  88882. }
  88883. }
  88884. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  88885. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  88886. this.world.addEventListener("preStep", impostor.beforeStep);
  88887. this.world.addEventListener("postStep", impostor.afterStep);
  88888. impostor.physicsBody.addShape(shape);
  88889. this.world.add(impostor.physicsBody);
  88890. //try to keep the body moving in the right direction by taking old properties.
  88891. //Should be tested!
  88892. if (oldBody) {
  88893. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  88894. impostor.physicsBody[param].copy(oldBody[param]);
  88895. });
  88896. }
  88897. this._processChildMeshes(impostor);
  88898. }
  88899. //now update the body's transformation
  88900. this._updatePhysicsBodyTransformation(impostor);
  88901. };
  88902. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  88903. var _this = this;
  88904. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  88905. var currentRotation = mainImpostor.object.rotationQuaternion;
  88906. if (meshChildren.length) {
  88907. var processMesh = function (localPosition, mesh) {
  88908. if (!currentRotation || !mesh.rotationQuaternion) {
  88909. return;
  88910. }
  88911. var childImpostor = mesh.getPhysicsImpostor();
  88912. if (childImpostor) {
  88913. var parent = childImpostor.parent;
  88914. if (parent !== mainImpostor) {
  88915. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  88916. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88917. if (childImpostor.physicsBody) {
  88918. _this.removePhysicsBody(childImpostor);
  88919. childImpostor.physicsBody = null;
  88920. }
  88921. childImpostor.parent = mainImpostor;
  88922. childImpostor.resetUpdateFlags();
  88923. 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));
  88924. //Add the mass of the children.
  88925. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88926. }
  88927. }
  88928. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88929. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88930. };
  88931. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88932. }
  88933. };
  88934. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88935. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88936. this.world.removeEventListener("preStep", impostor.beforeStep);
  88937. this.world.removeEventListener("postStep", impostor.afterStep);
  88938. this.world.remove(impostor.physicsBody);
  88939. };
  88940. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88941. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88942. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88943. if (!mainBody || !connectedBody) {
  88944. return;
  88945. }
  88946. var constraint;
  88947. var jointData = impostorJoint.joint.jointData;
  88948. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88949. var constraintData = {
  88950. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88951. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88952. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88953. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88954. maxForce: jointData.nativeParams.maxForce,
  88955. collideConnected: !!jointData.collision
  88956. };
  88957. switch (impostorJoint.joint.type) {
  88958. case BABYLON.PhysicsJoint.HingeJoint:
  88959. case BABYLON.PhysicsJoint.Hinge2Joint:
  88960. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88961. break;
  88962. case BABYLON.PhysicsJoint.DistanceJoint:
  88963. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88964. break;
  88965. case BABYLON.PhysicsJoint.SpringJoint:
  88966. var springData = jointData;
  88967. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88968. restLength: springData.length,
  88969. stiffness: springData.stiffness,
  88970. damping: springData.damping,
  88971. localAnchorA: constraintData.pivotA,
  88972. localAnchorB: constraintData.pivotB
  88973. });
  88974. break;
  88975. case BABYLON.PhysicsJoint.LockJoint:
  88976. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88977. break;
  88978. case BABYLON.PhysicsJoint.PointToPointJoint:
  88979. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88980. default:
  88981. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88982. break;
  88983. }
  88984. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88985. constraint.collideConnected = !!jointData.collision;
  88986. impostorJoint.joint.physicsJoint = constraint;
  88987. //don't add spring as constraint, as it is not one.
  88988. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88989. this.world.addConstraint(constraint);
  88990. }
  88991. else {
  88992. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  88993. constraint.applyForce();
  88994. };
  88995. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  88996. }
  88997. };
  88998. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88999. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89000. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  89001. }
  89002. else {
  89003. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89004. }
  89005. };
  89006. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  89007. var index;
  89008. var mat;
  89009. for (index = 0; index < this._physicsMaterials.length; index++) {
  89010. mat = this._physicsMaterials[index];
  89011. if (mat.friction === friction && mat.restitution === restitution) {
  89012. return mat;
  89013. }
  89014. }
  89015. var currentMat = new this.BJSCANNON.Material(name);
  89016. currentMat.friction = friction;
  89017. currentMat.restitution = restitution;
  89018. this._physicsMaterials.push(currentMat);
  89019. return currentMat;
  89020. };
  89021. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  89022. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  89023. };
  89024. CannonJSPlugin.prototype._createShape = function (impostor) {
  89025. var object = impostor.object;
  89026. var returnValue;
  89027. var extendSize = impostor.getObjectExtendSize();
  89028. switch (impostor.type) {
  89029. case BABYLON.PhysicsImpostor.SphereImpostor:
  89030. var radiusX = extendSize.x;
  89031. var radiusY = extendSize.y;
  89032. var radiusZ = extendSize.z;
  89033. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  89034. break;
  89035. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  89036. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89037. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  89038. break;
  89039. case BABYLON.PhysicsImpostor.BoxImpostor:
  89040. var box = extendSize.scale(0.5);
  89041. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  89042. break;
  89043. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89044. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  89045. returnValue = new this.BJSCANNON.Plane();
  89046. break;
  89047. case BABYLON.PhysicsImpostor.MeshImpostor:
  89048. // should transform the vertex data to world coordinates!!
  89049. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  89050. var rawFaces = object.getIndices ? object.getIndices() : [];
  89051. if (!rawVerts)
  89052. return;
  89053. // get only scale! so the object could transform correctly.
  89054. var oldPosition = object.position.clone();
  89055. var oldRotation = object.rotation && object.rotation.clone();
  89056. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  89057. object.position.copyFromFloats(0, 0, 0);
  89058. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89059. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89060. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89061. var transform = object.computeWorldMatrix(true);
  89062. // convert rawVerts to object space
  89063. var temp = new Array();
  89064. var index;
  89065. for (index = 0; index < rawVerts.length; index += 3) {
  89066. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  89067. }
  89068. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  89069. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  89070. //now set back the transformation!
  89071. object.position.copyFrom(oldPosition);
  89072. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  89073. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  89074. break;
  89075. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  89076. var oldPosition2 = object.position.clone();
  89077. var oldRotation2 = object.rotation && object.rotation.clone();
  89078. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  89079. object.position.copyFromFloats(0, 0, 0);
  89080. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89081. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89082. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89083. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  89084. returnValue = this._createHeightmap(object);
  89085. object.position.copyFrom(oldPosition2);
  89086. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  89087. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  89088. object.computeWorldMatrix(true);
  89089. break;
  89090. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89091. returnValue = new this.BJSCANNON.Particle();
  89092. break;
  89093. }
  89094. return returnValue;
  89095. };
  89096. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  89097. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89098. var transform = object.computeWorldMatrix(true);
  89099. // convert rawVerts to object space
  89100. var temp = new Array();
  89101. var index;
  89102. for (index = 0; index < pos.length; index += 3) {
  89103. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  89104. }
  89105. pos = temp;
  89106. var matrix = new Array();
  89107. //For now pointDepth will not be used and will be automatically calculated.
  89108. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  89109. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  89110. var boundingInfo = object.getBoundingInfo();
  89111. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  89112. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  89113. var elementSize = dim * 2 / arraySize;
  89114. for (var i = 0; i < pos.length; i = i + 3) {
  89115. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  89116. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  89117. var y = -pos[i + 2] + minY;
  89118. if (!matrix[x]) {
  89119. matrix[x] = [];
  89120. }
  89121. if (!matrix[x][z]) {
  89122. matrix[x][z] = y;
  89123. }
  89124. matrix[x][z] = Math.max(y, matrix[x][z]);
  89125. }
  89126. for (var x = 0; x <= arraySize; ++x) {
  89127. if (!matrix[x]) {
  89128. var loc = 1;
  89129. while (!matrix[(x + loc) % arraySize]) {
  89130. loc++;
  89131. }
  89132. matrix[x] = matrix[(x + loc) % arraySize].slice();
  89133. //console.log("missing x", x);
  89134. }
  89135. for (var z = 0; z <= arraySize; ++z) {
  89136. if (!matrix[x][z]) {
  89137. var loc = 1;
  89138. var newValue;
  89139. while (newValue === undefined) {
  89140. newValue = matrix[x][(z + loc++) % arraySize];
  89141. }
  89142. matrix[x][z] = newValue;
  89143. }
  89144. }
  89145. }
  89146. var shape = new this.BJSCANNON.Heightfield(matrix, {
  89147. elementSize: elementSize
  89148. });
  89149. //For future reference, needed for body transformation
  89150. shape.minY = minY;
  89151. return shape;
  89152. };
  89153. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  89154. var object = impostor.object;
  89155. //make sure it is updated...
  89156. object.computeWorldMatrix && object.computeWorldMatrix(true);
  89157. // The delta between the mesh position and the mesh bounding box center
  89158. var bInfo = object.getBoundingInfo();
  89159. if (!bInfo)
  89160. return;
  89161. var center = impostor.getObjectCenter();
  89162. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  89163. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  89164. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  89165. this._tmpPosition.copyFrom(center);
  89166. var quaternion = object.rotationQuaternion;
  89167. if (!quaternion) {
  89168. return;
  89169. }
  89170. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  89171. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  89172. //-90 DEG in X, precalculated
  89173. quaternion = quaternion.multiply(this._minus90X);
  89174. //Invert! (Precalculated, 90 deg in X)
  89175. //No need to clone. this will never change.
  89176. impostor.setDeltaRotation(this._plus90X);
  89177. }
  89178. //If it is a heightfield, if should be centered.
  89179. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  89180. var mesh = object;
  89181. var boundingInfo = mesh.getBoundingInfo();
  89182. //calculate the correct body position:
  89183. var rotationQuaternion = mesh.rotationQuaternion;
  89184. mesh.rotationQuaternion = this._tmpUnityRotation;
  89185. mesh.computeWorldMatrix(true);
  89186. //get original center with no rotation
  89187. var c = center.clone();
  89188. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  89189. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  89190. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  89191. mesh.setPreTransformMatrix(p);
  89192. mesh.computeWorldMatrix(true);
  89193. //calculate the translation
  89194. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  89195. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  89196. //add it inverted to the delta
  89197. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  89198. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  89199. //rotation is back
  89200. mesh.rotationQuaternion = rotationQuaternion;
  89201. mesh.setPreTransformMatrix(oldPivot);
  89202. mesh.computeWorldMatrix(true);
  89203. }
  89204. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  89205. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  89206. //this._tmpPosition.copyFrom(object.position);
  89207. }
  89208. impostor.setDeltaPosition(this._tmpDeltaPosition);
  89209. //Now update the impostor object
  89210. impostor.physicsBody.position.copy(this._tmpPosition);
  89211. impostor.physicsBody.quaternion.copy(quaternion);
  89212. };
  89213. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89214. impostor.object.position.copyFrom(impostor.physicsBody.position);
  89215. if (impostor.object.rotationQuaternion) {
  89216. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  89217. }
  89218. };
  89219. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89220. impostor.physicsBody.position.copy(newPosition);
  89221. impostor.physicsBody.quaternion.copy(newRotation);
  89222. };
  89223. CannonJSPlugin.prototype.isSupported = function () {
  89224. return this.BJSCANNON !== undefined;
  89225. };
  89226. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89227. impostor.physicsBody.velocity.copy(velocity);
  89228. };
  89229. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89230. impostor.physicsBody.angularVelocity.copy(velocity);
  89231. };
  89232. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89233. var v = impostor.physicsBody.velocity;
  89234. if (!v) {
  89235. return null;
  89236. }
  89237. return new BABYLON.Vector3(v.x, v.y, v.z);
  89238. };
  89239. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89240. var v = impostor.physicsBody.angularVelocity;
  89241. if (!v) {
  89242. return null;
  89243. }
  89244. return new BABYLON.Vector3(v.x, v.y, v.z);
  89245. };
  89246. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89247. impostor.physicsBody.mass = mass;
  89248. impostor.physicsBody.updateMassProperties();
  89249. };
  89250. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  89251. return impostor.physicsBody.mass;
  89252. };
  89253. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  89254. return impostor.physicsBody.material.friction;
  89255. };
  89256. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89257. impostor.physicsBody.material.friction = friction;
  89258. };
  89259. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89260. return impostor.physicsBody.material.restitution;
  89261. };
  89262. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89263. impostor.physicsBody.material.restitution = restitution;
  89264. };
  89265. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  89266. impostor.physicsBody.sleep();
  89267. };
  89268. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  89269. impostor.physicsBody.wakeUp();
  89270. };
  89271. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89272. joint.physicsJoint.distance = maxDistance;
  89273. };
  89274. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89275. // if (!motorIndex) {
  89276. // joint.physicsJoint.enableMotor();
  89277. // }
  89278. // }
  89279. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89280. // if (!motorIndex) {
  89281. // joint.physicsJoint.disableMotor();
  89282. // }
  89283. // }
  89284. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89285. if (!motorIndex) {
  89286. joint.physicsJoint.enableMotor();
  89287. joint.physicsJoint.setMotorSpeed(speed);
  89288. if (maxForce) {
  89289. this.setLimit(joint, maxForce);
  89290. }
  89291. }
  89292. };
  89293. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  89294. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  89295. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  89296. };
  89297. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89298. var body = impostor.physicsBody;
  89299. mesh.position.x = body.position.x;
  89300. mesh.position.y = body.position.y;
  89301. mesh.position.z = body.position.z;
  89302. if (mesh.rotationQuaternion) {
  89303. mesh.rotationQuaternion.x = body.quaternion.x;
  89304. mesh.rotationQuaternion.y = body.quaternion.y;
  89305. mesh.rotationQuaternion.z = body.quaternion.z;
  89306. mesh.rotationQuaternion.w = body.quaternion.w;
  89307. }
  89308. };
  89309. CannonJSPlugin.prototype.getRadius = function (impostor) {
  89310. var shape = impostor.physicsBody.shapes[0];
  89311. return shape.boundingSphereRadius;
  89312. };
  89313. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89314. var shape = impostor.physicsBody.shapes[0];
  89315. result.x = shape.halfExtents.x * 2;
  89316. result.y = shape.halfExtents.y * 2;
  89317. result.z = shape.halfExtents.z * 2;
  89318. };
  89319. CannonJSPlugin.prototype.dispose = function () {
  89320. };
  89321. CannonJSPlugin.prototype._extendNamespace = function () {
  89322. //this will force cannon to execute at least one step when using interpolation
  89323. var step_tmp1 = new this.BJSCANNON.Vec3();
  89324. var Engine = this.BJSCANNON;
  89325. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  89326. maxSubSteps = maxSubSteps || 10;
  89327. timeSinceLastCalled = timeSinceLastCalled || 0;
  89328. if (timeSinceLastCalled === 0) {
  89329. this.internalStep(dt);
  89330. this.time += dt;
  89331. }
  89332. else {
  89333. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  89334. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  89335. var t0 = performance.now();
  89336. for (var i = 0; i !== internalSteps; i++) {
  89337. this.internalStep(dt);
  89338. if (performance.now() - t0 > dt * 1000) {
  89339. break;
  89340. }
  89341. }
  89342. this.time += timeSinceLastCalled;
  89343. var h = this.time % dt;
  89344. var h_div_dt = h / dt;
  89345. var interpvelo = step_tmp1;
  89346. var bodies = this.bodies;
  89347. for (var j = 0; j !== bodies.length; j++) {
  89348. var b = bodies[j];
  89349. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  89350. b.position.vsub(b.previousPosition, interpvelo);
  89351. interpvelo.scale(h_div_dt, interpvelo);
  89352. b.position.vadd(interpvelo, b.interpolatedPosition);
  89353. }
  89354. else {
  89355. b.interpolatedPosition.copy(b.position);
  89356. b.interpolatedQuaternion.copy(b.quaternion);
  89357. }
  89358. }
  89359. }
  89360. };
  89361. };
  89362. return CannonJSPlugin;
  89363. }());
  89364. BABYLON.CannonJSPlugin = CannonJSPlugin;
  89365. })(BABYLON || (BABYLON = {}));
  89366. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  89367. var BABYLON;
  89368. (function (BABYLON) {
  89369. var OimoJSPlugin = /** @class */ (function () {
  89370. function OimoJSPlugin(iterations) {
  89371. this.name = "OimoJSPlugin";
  89372. this._tmpImpostorsArray = [];
  89373. this._tmpPositionVector = BABYLON.Vector3.Zero();
  89374. this.BJSOIMO = OIMO;
  89375. this.world = new this.BJSOIMO.World({
  89376. iterations: iterations
  89377. });
  89378. this.world.clear();
  89379. }
  89380. OimoJSPlugin.prototype.setGravity = function (gravity) {
  89381. this.world.gravity.copy(gravity);
  89382. };
  89383. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  89384. this.world.timeStep = timeStep;
  89385. };
  89386. OimoJSPlugin.prototype.getTimeStep = function () {
  89387. return this.world.timeStep;
  89388. };
  89389. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  89390. var _this = this;
  89391. impostors.forEach(function (impostor) {
  89392. impostor.beforeStep();
  89393. });
  89394. this.world.step();
  89395. impostors.forEach(function (impostor) {
  89396. impostor.afterStep();
  89397. //update the ordered impostors array
  89398. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  89399. });
  89400. //check for collisions
  89401. var contact = this.world.contacts;
  89402. while (contact !== null) {
  89403. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  89404. contact = contact.next;
  89405. continue;
  89406. }
  89407. //is this body colliding with any other? get the impostor
  89408. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  89409. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  89410. if (!mainImpostor || !collidingImpostor) {
  89411. contact = contact.next;
  89412. continue;
  89413. }
  89414. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  89415. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  89416. contact = contact.next;
  89417. }
  89418. };
  89419. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89420. var mass = impostor.physicsBody.mass;
  89421. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  89422. };
  89423. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89424. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  89425. this.applyImpulse(impostor, force, contactPoint);
  89426. };
  89427. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89428. var _this = this;
  89429. //parent-child relationship. Does this impostor has a parent impostor?
  89430. if (impostor.parent) {
  89431. if (impostor.physicsBody) {
  89432. this.removePhysicsBody(impostor);
  89433. //TODO is that needed?
  89434. impostor.forceUpdate();
  89435. }
  89436. return;
  89437. }
  89438. if (impostor.isBodyInitRequired()) {
  89439. var bodyConfig = {
  89440. name: impostor.uniqueId,
  89441. //Oimo must have mass, also for static objects.
  89442. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  89443. size: [],
  89444. type: [],
  89445. pos: [],
  89446. posShape: [],
  89447. rot: [],
  89448. rotShape: [],
  89449. move: impostor.getParam("mass") !== 0,
  89450. density: impostor.getParam("mass"),
  89451. friction: impostor.getParam("friction"),
  89452. restitution: impostor.getParam("restitution"),
  89453. //Supporting older versions of Oimo
  89454. world: this.world
  89455. };
  89456. var impostors = [impostor];
  89457. var addToArray = function (parent) {
  89458. if (!parent.getChildMeshes)
  89459. return;
  89460. parent.getChildMeshes().forEach(function (m) {
  89461. if (m.physicsImpostor) {
  89462. impostors.push(m.physicsImpostor);
  89463. //m.physicsImpostor._init();
  89464. }
  89465. });
  89466. };
  89467. addToArray(impostor.object);
  89468. var checkWithEpsilon_1 = function (value) {
  89469. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  89470. };
  89471. var globalQuaternion_1 = new BABYLON.Quaternion();
  89472. impostors.forEach(function (i) {
  89473. if (!i.object.rotationQuaternion) {
  89474. return;
  89475. }
  89476. //get the correct bounding box
  89477. var oldQuaternion = i.object.rotationQuaternion;
  89478. globalQuaternion_1 = oldQuaternion.clone();
  89479. var rot = oldQuaternion.toEulerAngles();
  89480. var extendSize = i.getObjectExtendSize();
  89481. var radToDeg = 57.295779513082320876;
  89482. if (i === impostor) {
  89483. var center = impostor.getObjectCenter();
  89484. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  89485. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  89486. //Can also use Array.prototype.push.apply
  89487. bodyConfig.pos.push(center.x);
  89488. bodyConfig.pos.push(center.y);
  89489. bodyConfig.pos.push(center.z);
  89490. bodyConfig.posShape.push(0, 0, 0);
  89491. //tmp solution
  89492. bodyConfig.rot.push(0);
  89493. bodyConfig.rot.push(0);
  89494. bodyConfig.rot.push(0);
  89495. bodyConfig.rotShape.push(0, 0, 0);
  89496. }
  89497. else {
  89498. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  89499. bodyConfig.posShape.push(localPosition.x);
  89500. bodyConfig.posShape.push(localPosition.y);
  89501. bodyConfig.posShape.push(localPosition.z);
  89502. bodyConfig.pos.push(0, 0, 0);
  89503. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  89504. bodyConfig.rot.push(0);
  89505. bodyConfig.rot.push(0);
  89506. bodyConfig.rot.push(0);
  89507. bodyConfig.rotShape.push(rot.x * radToDeg);
  89508. bodyConfig.rotShape.push(rot.y * radToDeg);
  89509. bodyConfig.rotShape.push(rot.z * radToDeg);
  89510. }
  89511. // register mesh
  89512. switch (i.type) {
  89513. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89514. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  89515. case BABYLON.PhysicsImpostor.SphereImpostor:
  89516. var radiusX = extendSize.x;
  89517. var radiusY = extendSize.y;
  89518. var radiusZ = extendSize.z;
  89519. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  89520. bodyConfig.type.push('sphere');
  89521. //due to the way oimo works with compounds, add 3 times
  89522. bodyConfig.size.push(size);
  89523. bodyConfig.size.push(size);
  89524. bodyConfig.size.push(size);
  89525. break;
  89526. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89527. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  89528. var sizeY = checkWithEpsilon_1(extendSize.y);
  89529. bodyConfig.type.push('cylinder');
  89530. bodyConfig.size.push(sizeX);
  89531. bodyConfig.size.push(sizeY);
  89532. //due to the way oimo works with compounds, add one more value.
  89533. bodyConfig.size.push(sizeY);
  89534. break;
  89535. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89536. case BABYLON.PhysicsImpostor.BoxImpostor:
  89537. default:
  89538. var sizeX = checkWithEpsilon_1(extendSize.x);
  89539. var sizeY = checkWithEpsilon_1(extendSize.y);
  89540. var sizeZ = checkWithEpsilon_1(extendSize.z);
  89541. bodyConfig.type.push('box');
  89542. //if (i === impostor) {
  89543. bodyConfig.size.push(sizeX);
  89544. bodyConfig.size.push(sizeY);
  89545. bodyConfig.size.push(sizeZ);
  89546. //} else {
  89547. // bodyConfig.size.push(0,0,0);
  89548. //}
  89549. break;
  89550. }
  89551. //actually not needed, but hey...
  89552. i.object.rotationQuaternion = oldQuaternion;
  89553. });
  89554. impostor.physicsBody = this.world.add(bodyConfig);
  89555. // set the quaternion, ignoring the previously defined (euler) rotation
  89556. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  89557. // update with delta 0, so the body will reveive the new rotation.
  89558. impostor.physicsBody.updatePosition(0);
  89559. }
  89560. else {
  89561. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  89562. }
  89563. impostor.setDeltaPosition(this._tmpPositionVector);
  89564. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  89565. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  89566. };
  89567. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89568. //impostor.physicsBody.dispose();
  89569. //Same as : (older oimo versions)
  89570. this.world.removeRigidBody(impostor.physicsBody);
  89571. };
  89572. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89573. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89574. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89575. if (!mainBody || !connectedBody) {
  89576. return;
  89577. }
  89578. var jointData = impostorJoint.joint.jointData;
  89579. var options = jointData.nativeParams || {};
  89580. var type;
  89581. var nativeJointData = {
  89582. body1: mainBody,
  89583. body2: connectedBody,
  89584. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  89585. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  89586. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  89587. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  89588. min: options.min,
  89589. max: options.max,
  89590. collision: options.collision || jointData.collision,
  89591. spring: options.spring,
  89592. //supporting older version of Oimo
  89593. world: this.world
  89594. };
  89595. switch (impostorJoint.joint.type) {
  89596. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89597. type = "jointBall";
  89598. break;
  89599. case BABYLON.PhysicsJoint.SpringJoint:
  89600. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  89601. var springData = jointData;
  89602. nativeJointData.min = springData.length || nativeJointData.min;
  89603. //Max should also be set, just make sure it is at least min
  89604. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  89605. case BABYLON.PhysicsJoint.DistanceJoint:
  89606. type = "jointDistance";
  89607. nativeJointData.max = jointData.maxDistance;
  89608. break;
  89609. case BABYLON.PhysicsJoint.PrismaticJoint:
  89610. type = "jointPrisme";
  89611. break;
  89612. case BABYLON.PhysicsJoint.SliderJoint:
  89613. type = "jointSlide";
  89614. break;
  89615. case BABYLON.PhysicsJoint.WheelJoint:
  89616. type = "jointWheel";
  89617. break;
  89618. case BABYLON.PhysicsJoint.HingeJoint:
  89619. default:
  89620. type = "jointHinge";
  89621. break;
  89622. }
  89623. nativeJointData.type = type;
  89624. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  89625. };
  89626. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89627. //Bug in Oimo prevents us from disposing a joint in the playground
  89628. //joint.joint.physicsJoint.dispose();
  89629. //So we will bruteforce it!
  89630. try {
  89631. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  89632. }
  89633. catch (e) {
  89634. BABYLON.Tools.Warn(e);
  89635. }
  89636. };
  89637. OimoJSPlugin.prototype.isSupported = function () {
  89638. return this.BJSOIMO !== undefined;
  89639. };
  89640. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89641. if (!impostor.physicsBody.sleeping) {
  89642. //TODO check that
  89643. /*if (impostor.physicsBody.shapes.next) {
  89644. var parentShape = this._getLastShape(impostor.physicsBody);
  89645. impostor.object.position.copyFrom(parentShape.position);
  89646. console.log(parentShape.position);
  89647. } else {*/
  89648. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  89649. //}
  89650. if (impostor.object.rotationQuaternion) {
  89651. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  89652. }
  89653. }
  89654. };
  89655. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89656. var body = impostor.physicsBody;
  89657. body.position.copy(newPosition);
  89658. body.orientation.copy(newRotation);
  89659. body.syncShapes();
  89660. body.awake();
  89661. };
  89662. /*private _getLastShape(body: any): any {
  89663. var lastShape = body.shapes;
  89664. while (lastShape.next) {
  89665. lastShape = lastShape.next;
  89666. }
  89667. return lastShape;
  89668. }*/
  89669. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89670. impostor.physicsBody.linearVelocity.copy(velocity);
  89671. };
  89672. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89673. impostor.physicsBody.angularVelocity.copy(velocity);
  89674. };
  89675. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89676. var v = impostor.physicsBody.linearVelocity;
  89677. if (!v) {
  89678. return null;
  89679. }
  89680. return new BABYLON.Vector3(v.x, v.y, v.z);
  89681. };
  89682. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89683. var v = impostor.physicsBody.angularVelocity;
  89684. if (!v) {
  89685. return null;
  89686. }
  89687. return new BABYLON.Vector3(v.x, v.y, v.z);
  89688. };
  89689. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89690. var staticBody = mass === 0;
  89691. //this will actually set the body's density and not its mass.
  89692. //But this is how oimo treats the mass variable.
  89693. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  89694. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89695. };
  89696. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89697. return impostor.physicsBody.shapes.density;
  89698. };
  89699. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89700. return impostor.physicsBody.shapes.friction;
  89701. };
  89702. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89703. impostor.physicsBody.shapes.friction = friction;
  89704. };
  89705. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89706. return impostor.physicsBody.shapes.restitution;
  89707. };
  89708. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89709. impostor.physicsBody.shapes.restitution = restitution;
  89710. };
  89711. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89712. impostor.physicsBody.sleep();
  89713. };
  89714. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89715. impostor.physicsBody.awake();
  89716. };
  89717. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89718. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89719. if (minDistance !== void 0) {
  89720. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89721. }
  89722. };
  89723. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89724. //TODO separate rotational and transational motors.
  89725. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89726. if (motor) {
  89727. motor.setMotor(speed, maxForce);
  89728. }
  89729. };
  89730. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89731. //TODO separate rotational and transational motors.
  89732. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89733. if (motor) {
  89734. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89735. }
  89736. };
  89737. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89738. var body = impostor.physicsBody;
  89739. mesh.position.x = body.position.x;
  89740. mesh.position.y = body.position.y;
  89741. mesh.position.z = body.position.z;
  89742. if (mesh.rotationQuaternion) {
  89743. mesh.rotationQuaternion.x = body.orientation.x;
  89744. mesh.rotationQuaternion.y = body.orientation.y;
  89745. mesh.rotationQuaternion.z = body.orientation.z;
  89746. mesh.rotationQuaternion.w = body.orientation.s;
  89747. }
  89748. };
  89749. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89750. return impostor.physicsBody.shapes.radius;
  89751. };
  89752. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89753. var shape = impostor.physicsBody.shapes;
  89754. result.x = shape.halfWidth * 2;
  89755. result.y = shape.halfHeight * 2;
  89756. result.z = shape.halfDepth * 2;
  89757. };
  89758. OimoJSPlugin.prototype.dispose = function () {
  89759. this.world.clear();
  89760. };
  89761. return OimoJSPlugin;
  89762. }());
  89763. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89764. })(BABYLON || (BABYLON = {}));
  89765. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89766. var BABYLON;
  89767. (function (BABYLON) {
  89768. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89769. // All values and structures referenced from:
  89770. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89771. var DDS_MAGIC = 0x20534444;
  89772. var
  89773. //DDSD_CAPS = 0x1,
  89774. //DDSD_HEIGHT = 0x2,
  89775. //DDSD_WIDTH = 0x4,
  89776. //DDSD_PITCH = 0x8,
  89777. //DDSD_PIXELFORMAT = 0x1000,
  89778. DDSD_MIPMAPCOUNT = 0x20000;
  89779. //DDSD_LINEARSIZE = 0x80000,
  89780. //DDSD_DEPTH = 0x800000;
  89781. // var DDSCAPS_COMPLEX = 0x8,
  89782. // DDSCAPS_MIPMAP = 0x400000,
  89783. // DDSCAPS_TEXTURE = 0x1000;
  89784. var DDSCAPS2_CUBEMAP = 0x200;
  89785. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  89786. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  89787. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  89788. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  89789. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  89790. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  89791. // DDSCAPS2_VOLUME = 0x200000;
  89792. var
  89793. //DDPF_ALPHAPIXELS = 0x1,
  89794. //DDPF_ALPHA = 0x2,
  89795. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  89796. //DDPF_YUV = 0x200,
  89797. DDPF_LUMINANCE = 0x20000;
  89798. function FourCCToInt32(value) {
  89799. return value.charCodeAt(0) +
  89800. (value.charCodeAt(1) << 8) +
  89801. (value.charCodeAt(2) << 16) +
  89802. (value.charCodeAt(3) << 24);
  89803. }
  89804. function Int32ToFourCC(value) {
  89805. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  89806. }
  89807. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  89808. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  89809. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  89810. var FOURCC_DX10 = FourCCToInt32("DX10");
  89811. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  89812. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  89813. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  89814. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  89815. var headerLengthInt = 31; // The header length in 32 bit ints
  89816. // Offsets into the header array
  89817. var off_magic = 0;
  89818. var off_size = 1;
  89819. var off_flags = 2;
  89820. var off_height = 3;
  89821. var off_width = 4;
  89822. var off_mipmapCount = 7;
  89823. var off_pfFlags = 20;
  89824. var off_pfFourCC = 21;
  89825. var off_RGBbpp = 22;
  89826. var off_RMask = 23;
  89827. var off_GMask = 24;
  89828. var off_BMask = 25;
  89829. var off_AMask = 26;
  89830. // var off_caps1 = 27;
  89831. var off_caps2 = 28;
  89832. // var off_caps3 = 29;
  89833. // var off_caps4 = 30;
  89834. var off_dxgiFormat = 32;
  89835. ;
  89836. var DDSTools = /** @class */ (function () {
  89837. function DDSTools() {
  89838. }
  89839. DDSTools.GetDDSInfo = function (arrayBuffer) {
  89840. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89841. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  89842. var mipmapCount = 1;
  89843. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  89844. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89845. }
  89846. var fourCC = header[off_pfFourCC];
  89847. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  89848. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89849. switch (fourCC) {
  89850. case FOURCC_D3DFMT_R16G16B16A16F:
  89851. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89852. break;
  89853. case FOURCC_D3DFMT_R32G32B32A32F:
  89854. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89855. break;
  89856. case FOURCC_DX10:
  89857. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  89858. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89859. break;
  89860. }
  89861. }
  89862. return {
  89863. width: header[off_width],
  89864. height: header[off_height],
  89865. mipmapCount: mipmapCount,
  89866. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  89867. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  89868. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  89869. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  89870. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  89871. dxgiFormat: dxgiFormat,
  89872. textureType: textureType
  89873. };
  89874. };
  89875. DDSTools._ToHalfFloat = function (value) {
  89876. if (!DDSTools._FloatView) {
  89877. DDSTools._FloatView = new Float32Array(1);
  89878. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  89879. }
  89880. DDSTools._FloatView[0] = value;
  89881. var x = DDSTools._Int32View[0];
  89882. var bits = (x >> 16) & 0x8000; /* Get the sign */
  89883. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  89884. var e = (x >> 23) & 0xff; /* Using int is faster here */
  89885. /* If zero, or denormal, or exponent underflows too much for a denormal
  89886. * half, return signed zero. */
  89887. if (e < 103) {
  89888. return bits;
  89889. }
  89890. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  89891. if (e > 142) {
  89892. bits |= 0x7c00;
  89893. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  89894. * not Inf, so make sure we set one mantissa bit too. */
  89895. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  89896. return bits;
  89897. }
  89898. /* If exponent underflows but not too much, return a denormal */
  89899. if (e < 113) {
  89900. m |= 0x0800;
  89901. /* Extra rounding may overflow and set mantissa to 0 and exponent
  89902. * to 1, which is OK. */
  89903. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  89904. return bits;
  89905. }
  89906. bits |= ((e - 112) << 10) | (m >> 1);
  89907. bits += m & 1;
  89908. return bits;
  89909. };
  89910. DDSTools._FromHalfFloat = function (value) {
  89911. var s = (value & 0x8000) >> 15;
  89912. var e = (value & 0x7C00) >> 10;
  89913. var f = value & 0x03FF;
  89914. if (e === 0) {
  89915. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  89916. }
  89917. else if (e == 0x1F) {
  89918. return f ? NaN : ((s ? -1 : 1) * Infinity);
  89919. }
  89920. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  89921. };
  89922. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89923. var destArray = new Float32Array(dataLength);
  89924. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89925. var index = 0;
  89926. for (var y = 0; y < height; y++) {
  89927. for (var x = 0; x < width; x++) {
  89928. var srcPos = (x + y * width) * 4;
  89929. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89930. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89931. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89932. if (DDSTools.StoreLODInAlphaChannel) {
  89933. destArray[index + 3] = lod;
  89934. }
  89935. else {
  89936. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89937. }
  89938. index += 4;
  89939. }
  89940. }
  89941. return destArray;
  89942. };
  89943. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89944. if (DDSTools.StoreLODInAlphaChannel) {
  89945. var destArray = new Uint16Array(dataLength);
  89946. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89947. var index = 0;
  89948. for (var y = 0; y < height; y++) {
  89949. for (var x = 0; x < width; x++) {
  89950. var srcPos = (x + y * width) * 4;
  89951. destArray[index] = srcData[srcPos];
  89952. destArray[index + 1] = srcData[srcPos + 1];
  89953. destArray[index + 2] = srcData[srcPos + 2];
  89954. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89955. index += 4;
  89956. }
  89957. }
  89958. return destArray;
  89959. }
  89960. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89961. };
  89962. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89963. if (DDSTools.StoreLODInAlphaChannel) {
  89964. var destArray = new Float32Array(dataLength);
  89965. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89966. var index = 0;
  89967. for (var y = 0; y < height; y++) {
  89968. for (var x = 0; x < width; x++) {
  89969. var srcPos = (x + y * width) * 4;
  89970. destArray[index] = srcData[srcPos];
  89971. destArray[index + 1] = srcData[srcPos + 1];
  89972. destArray[index + 2] = srcData[srcPos + 2];
  89973. destArray[index + 3] = lod;
  89974. index += 4;
  89975. }
  89976. }
  89977. return destArray;
  89978. }
  89979. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89980. };
  89981. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89982. var destArray = new Uint8Array(dataLength);
  89983. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89984. var index = 0;
  89985. for (var y = 0; y < height; y++) {
  89986. for (var x = 0; x < width; x++) {
  89987. var srcPos = (x + y * width) * 4;
  89988. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89989. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89990. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89991. if (DDSTools.StoreLODInAlphaChannel) {
  89992. destArray[index + 3] = lod;
  89993. }
  89994. else {
  89995. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89996. }
  89997. index += 4;
  89998. }
  89999. }
  90000. return destArray;
  90001. };
  90002. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90003. var destArray = new Uint8Array(dataLength);
  90004. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90005. var index = 0;
  90006. for (var y = 0; y < height; y++) {
  90007. for (var x = 0; x < width; x++) {
  90008. var srcPos = (x + y * width) * 4;
  90009. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  90010. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  90011. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  90012. if (DDSTools.StoreLODInAlphaChannel) {
  90013. destArray[index + 3] = lod;
  90014. }
  90015. else {
  90016. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  90017. }
  90018. index += 4;
  90019. }
  90020. }
  90021. return destArray;
  90022. };
  90023. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  90024. var byteArray = new Uint8Array(dataLength);
  90025. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90026. var index = 0;
  90027. for (var y = 0; y < height; y++) {
  90028. for (var x = 0; x < width; x++) {
  90029. var srcPos = (x + y * width) * 4;
  90030. byteArray[index] = srcData[srcPos + rOffset];
  90031. byteArray[index + 1] = srcData[srcPos + gOffset];
  90032. byteArray[index + 2] = srcData[srcPos + bOffset];
  90033. byteArray[index + 3] = srcData[srcPos + aOffset];
  90034. index += 4;
  90035. }
  90036. }
  90037. return byteArray;
  90038. };
  90039. DDSTools._ExtractLongWordOrder = function (value) {
  90040. if (value === 0 || value === 255 || value === -16777216) {
  90041. return 0;
  90042. }
  90043. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  90044. };
  90045. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  90046. var byteArray = new Uint8Array(dataLength);
  90047. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90048. var index = 0;
  90049. for (var y = 0; y < height; y++) {
  90050. for (var x = 0; x < width; x++) {
  90051. var srcPos = (x + y * width) * 3;
  90052. byteArray[index] = srcData[srcPos + rOffset];
  90053. byteArray[index + 1] = srcData[srcPos + gOffset];
  90054. byteArray[index + 2] = srcData[srcPos + bOffset];
  90055. index += 3;
  90056. }
  90057. }
  90058. return byteArray;
  90059. };
  90060. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  90061. var byteArray = new Uint8Array(dataLength);
  90062. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90063. var index = 0;
  90064. for (var y = 0; y < height; y++) {
  90065. for (var x = 0; x < width; x++) {
  90066. var srcPos = (x + y * width);
  90067. byteArray[index] = srcData[srcPos];
  90068. index++;
  90069. }
  90070. }
  90071. return byteArray;
  90072. };
  90073. /**
  90074. * Uploads DDS Levels to a Babylon Texture
  90075. * @hidden
  90076. */
  90077. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  90078. if (lodIndex === void 0) { lodIndex = -1; }
  90079. var sphericalPolynomialFaces = null;
  90080. if (info.sphericalPolynomial) {
  90081. sphericalPolynomialFaces = new Array();
  90082. }
  90083. var ext = engine.getCaps().s3tc;
  90084. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90085. var fourCC, width, height, dataLength = 0, dataOffset;
  90086. var byteArray, mipmapCount, mip;
  90087. var internalCompressedFormat = 0;
  90088. var blockBytes = 1;
  90089. if (header[off_magic] !== DDS_MAGIC) {
  90090. BABYLON.Tools.Error("Invalid magic number in DDS header");
  90091. return;
  90092. }
  90093. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  90094. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  90095. return;
  90096. }
  90097. if (info.isCompressed && !ext) {
  90098. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  90099. return;
  90100. }
  90101. var bpp = header[off_RGBbpp];
  90102. dataOffset = header[off_size] + 4;
  90103. var computeFormats = false;
  90104. if (info.isFourCC) {
  90105. fourCC = header[off_pfFourCC];
  90106. switch (fourCC) {
  90107. case FOURCC_DXT1:
  90108. blockBytes = 8;
  90109. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  90110. break;
  90111. case FOURCC_DXT3:
  90112. blockBytes = 16;
  90113. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  90114. break;
  90115. case FOURCC_DXT5:
  90116. blockBytes = 16;
  90117. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  90118. break;
  90119. case FOURCC_D3DFMT_R16G16B16A16F:
  90120. computeFormats = true;
  90121. break;
  90122. case FOURCC_D3DFMT_R32G32B32A32F:
  90123. computeFormats = true;
  90124. break;
  90125. case FOURCC_DX10:
  90126. // There is an additionnal header so dataOffset need to be changed
  90127. dataOffset += 5 * 4; // 5 uints
  90128. var supported = false;
  90129. switch (info.dxgiFormat) {
  90130. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  90131. computeFormats = true;
  90132. supported = true;
  90133. break;
  90134. case DXGI_FORMAT_B8G8R8X8_UNORM:
  90135. info.isRGB = true;
  90136. info.isFourCC = false;
  90137. bpp = 32;
  90138. supported = true;
  90139. break;
  90140. }
  90141. if (supported) {
  90142. break;
  90143. }
  90144. default:
  90145. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  90146. return;
  90147. }
  90148. }
  90149. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  90150. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  90151. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  90152. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  90153. if (computeFormats) {
  90154. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  90155. }
  90156. mipmapCount = 1;
  90157. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  90158. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90159. }
  90160. for (var face = 0; face < faces; face++) {
  90161. width = header[off_width];
  90162. height = header[off_height];
  90163. for (mip = 0; mip < mipmapCount; ++mip) {
  90164. if (lodIndex === -1 || lodIndex === mip) {
  90165. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  90166. var i = (lodIndex === -1) ? mip : 0;
  90167. if (!info.isCompressed && info.isFourCC) {
  90168. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90169. dataLength = width * height * 4;
  90170. var floatArray = null;
  90171. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  90172. if (bpp === 128) {
  90173. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90174. if (sphericalPolynomialFaces && i == 0) {
  90175. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90176. }
  90177. }
  90178. else if (bpp === 64) {
  90179. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90180. if (sphericalPolynomialFaces && i == 0) {
  90181. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90182. }
  90183. }
  90184. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90185. }
  90186. else {
  90187. if (bpp === 128) {
  90188. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90189. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90190. if (sphericalPolynomialFaces && i == 0) {
  90191. sphericalPolynomialFaces.push(floatArray);
  90192. }
  90193. }
  90194. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  90195. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90196. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90197. if (sphericalPolynomialFaces && i == 0) {
  90198. sphericalPolynomialFaces.push(floatArray);
  90199. }
  90200. }
  90201. else { // 64
  90202. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90203. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90204. if (sphericalPolynomialFaces && i == 0) {
  90205. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90206. }
  90207. }
  90208. }
  90209. if (floatArray) {
  90210. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  90211. }
  90212. }
  90213. else if (info.isRGB) {
  90214. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90215. if (bpp === 24) {
  90216. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  90217. dataLength = width * height * 3;
  90218. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  90219. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90220. }
  90221. else { // 32
  90222. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90223. dataLength = width * height * 4;
  90224. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  90225. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90226. }
  90227. }
  90228. else if (info.isLuminance) {
  90229. var unpackAlignment = engine._getUnpackAlignement();
  90230. var unpaddedRowSize = width;
  90231. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  90232. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  90233. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  90234. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  90235. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90236. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90237. }
  90238. else {
  90239. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  90240. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  90241. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90242. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  90243. }
  90244. }
  90245. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  90246. width *= 0.5;
  90247. height *= 0.5;
  90248. width = Math.max(1.0, width);
  90249. height = Math.max(1.0, height);
  90250. }
  90251. if (currentFace !== undefined) {
  90252. // Loading a single face
  90253. break;
  90254. }
  90255. }
  90256. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  90257. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  90258. size: header[off_width],
  90259. right: sphericalPolynomialFaces[0],
  90260. left: sphericalPolynomialFaces[1],
  90261. up: sphericalPolynomialFaces[2],
  90262. down: sphericalPolynomialFaces[3],
  90263. front: sphericalPolynomialFaces[4],
  90264. back: sphericalPolynomialFaces[5],
  90265. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  90266. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  90267. gammaSpace: false,
  90268. });
  90269. }
  90270. else {
  90271. info.sphericalPolynomial = undefined;
  90272. }
  90273. };
  90274. DDSTools.StoreLODInAlphaChannel = false;
  90275. return DDSTools;
  90276. }());
  90277. BABYLON.DDSTools = DDSTools;
  90278. })(BABYLON || (BABYLON = {}));
  90279. //# sourceMappingURL=babylon.dds.js.map
  90280. var BABYLON;
  90281. (function (BABYLON) {
  90282. /**
  90283. * Implementation of the DDS Texture Loader.
  90284. */
  90285. var DDSTextureLoader = /** @class */ (function () {
  90286. function DDSTextureLoader() {
  90287. /**
  90288. * Defines wether the loader supports cascade loading the different faces.
  90289. */
  90290. this.supportCascades = true;
  90291. }
  90292. /**
  90293. * This returns if the loader support the current file information.
  90294. * @param extension defines the file extension of the file being loaded
  90295. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90296. * @param fallback defines the fallback internal texture if any
  90297. * @param isBase64 defines whether the texture is encoded as a base64
  90298. * @param isBuffer defines whether the texture data are stored as a buffer
  90299. * @returns true if the loader can load the specified file
  90300. */
  90301. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90302. return extension.indexOf(".dds") === 0;
  90303. };
  90304. /**
  90305. * Transform the url before loading if required.
  90306. * @param rootUrl the url of the texture
  90307. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90308. * @returns the transformed texture
  90309. */
  90310. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90311. return rootUrl;
  90312. };
  90313. /**
  90314. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90315. * @param rootUrl the url of the texture
  90316. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90317. * @returns the fallback texture
  90318. */
  90319. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90320. return null;
  90321. };
  90322. /**
  90323. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90324. * @param data contains the texture data
  90325. * @param texture defines the BabylonJS internal texture
  90326. * @param createPolynomials will be true if polynomials have been requested
  90327. * @param onLoad defines the callback to trigger once the texture is ready
  90328. * @param onError defines the callback to trigger in case of error
  90329. */
  90330. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  90331. var engine = texture.getEngine();
  90332. var info;
  90333. var loadMipmap = false;
  90334. if (Array.isArray(imgs)) {
  90335. for (var index = 0; index < imgs.length; index++) {
  90336. var data_1 = imgs[index];
  90337. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  90338. texture.width = info.width;
  90339. texture.height = info.height;
  90340. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  90341. engine._unpackFlipY(info.isCompressed);
  90342. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  90343. if (!info.isFourCC && info.mipmapCount === 1) {
  90344. engine.generateMipMapsForCubemap(texture);
  90345. }
  90346. }
  90347. }
  90348. else {
  90349. var data = imgs;
  90350. info = BABYLON.DDSTools.GetDDSInfo(data);
  90351. texture.width = info.width;
  90352. texture.height = info.height;
  90353. if (createPolynomials) {
  90354. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  90355. }
  90356. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  90357. engine._unpackFlipY(info.isCompressed);
  90358. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  90359. if (!info.isFourCC && info.mipmapCount === 1) {
  90360. engine.generateMipMapsForCubemap(texture);
  90361. }
  90362. }
  90363. engine._setCubeMapTextureParams(loadMipmap);
  90364. texture.isReady = true;
  90365. if (onLoad) {
  90366. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  90367. }
  90368. };
  90369. /**
  90370. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90371. * @param data contains the texture data
  90372. * @param texture defines the BabylonJS internal texture
  90373. * @param callback defines the method to call once ready to upload
  90374. */
  90375. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  90376. var info = BABYLON.DDSTools.GetDDSInfo(data);
  90377. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  90378. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  90379. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  90380. });
  90381. };
  90382. return DDSTextureLoader;
  90383. }());
  90384. // Register the loader.
  90385. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  90386. })(BABYLON || (BABYLON = {}));
  90387. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  90388. var BABYLON;
  90389. (function (BABYLON) {
  90390. /*
  90391. * Based on jsTGALoader - Javascript loader for TGA file
  90392. * By Vincent Thibault
  90393. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  90394. */
  90395. var TGATools = /** @class */ (function () {
  90396. function TGATools() {
  90397. }
  90398. TGATools.GetTGAHeader = function (data) {
  90399. var offset = 0;
  90400. var header = {
  90401. id_length: data[offset++],
  90402. colormap_type: data[offset++],
  90403. image_type: data[offset++],
  90404. colormap_index: data[offset++] | data[offset++] << 8,
  90405. colormap_length: data[offset++] | data[offset++] << 8,
  90406. colormap_size: data[offset++],
  90407. origin: [
  90408. data[offset++] | data[offset++] << 8,
  90409. data[offset++] | data[offset++] << 8
  90410. ],
  90411. width: data[offset++] | data[offset++] << 8,
  90412. height: data[offset++] | data[offset++] << 8,
  90413. pixel_size: data[offset++],
  90414. flags: data[offset++]
  90415. };
  90416. return header;
  90417. };
  90418. /**
  90419. * Uploads TGA content to a Babylon Texture
  90420. * @hidden
  90421. */
  90422. TGATools.UploadContent = function (texture, data) {
  90423. // Not enough data to contain header ?
  90424. if (data.length < 19) {
  90425. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  90426. return;
  90427. }
  90428. // Read Header
  90429. var offset = 18;
  90430. var header = TGATools.GetTGAHeader(data);
  90431. // Assume it's a valid Targa file.
  90432. if (header.id_length + offset > data.length) {
  90433. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  90434. return;
  90435. }
  90436. // Skip not needed data
  90437. offset += header.id_length;
  90438. var use_rle = false;
  90439. var use_pal = false;
  90440. var use_grey = false;
  90441. // Get some informations.
  90442. switch (header.image_type) {
  90443. case TGATools._TYPE_RLE_INDEXED:
  90444. use_rle = true;
  90445. case TGATools._TYPE_INDEXED:
  90446. use_pal = true;
  90447. break;
  90448. case TGATools._TYPE_RLE_RGB:
  90449. use_rle = true;
  90450. case TGATools._TYPE_RGB:
  90451. // use_rgb = true;
  90452. break;
  90453. case TGATools._TYPE_RLE_GREY:
  90454. use_rle = true;
  90455. case TGATools._TYPE_GREY:
  90456. use_grey = true;
  90457. break;
  90458. }
  90459. var pixel_data;
  90460. // var numAlphaBits = header.flags & 0xf;
  90461. var pixel_size = header.pixel_size >> 3;
  90462. var pixel_total = header.width * header.height * pixel_size;
  90463. // Read palettes
  90464. var palettes;
  90465. if (use_pal) {
  90466. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  90467. }
  90468. // Read LRE
  90469. if (use_rle) {
  90470. pixel_data = new Uint8Array(pixel_total);
  90471. var c, count, i;
  90472. var localOffset = 0;
  90473. var pixels = new Uint8Array(pixel_size);
  90474. while (offset < pixel_total && localOffset < pixel_total) {
  90475. c = data[offset++];
  90476. count = (c & 0x7f) + 1;
  90477. // RLE pixels
  90478. if (c & 0x80) {
  90479. // Bind pixel tmp array
  90480. for (i = 0; i < pixel_size; ++i) {
  90481. pixels[i] = data[offset++];
  90482. }
  90483. // Copy pixel array
  90484. for (i = 0; i < count; ++i) {
  90485. pixel_data.set(pixels, localOffset + i * pixel_size);
  90486. }
  90487. localOffset += pixel_size * count;
  90488. }
  90489. // Raw pixels
  90490. else {
  90491. count *= pixel_size;
  90492. for (i = 0; i < count; ++i) {
  90493. pixel_data[localOffset + i] = data[offset++];
  90494. }
  90495. localOffset += count;
  90496. }
  90497. }
  90498. }
  90499. // RAW Pixels
  90500. else {
  90501. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  90502. }
  90503. // Load to texture
  90504. var x_start, y_start, x_step, y_step, y_end, x_end;
  90505. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  90506. default:
  90507. case TGATools._ORIGIN_UL:
  90508. x_start = 0;
  90509. x_step = 1;
  90510. x_end = header.width;
  90511. y_start = 0;
  90512. y_step = 1;
  90513. y_end = header.height;
  90514. break;
  90515. case TGATools._ORIGIN_BL:
  90516. x_start = 0;
  90517. x_step = 1;
  90518. x_end = header.width;
  90519. y_start = header.height - 1;
  90520. y_step = -1;
  90521. y_end = -1;
  90522. break;
  90523. case TGATools._ORIGIN_UR:
  90524. x_start = header.width - 1;
  90525. x_step = -1;
  90526. x_end = -1;
  90527. y_start = 0;
  90528. y_step = 1;
  90529. y_end = header.height;
  90530. break;
  90531. case TGATools._ORIGIN_BR:
  90532. x_start = header.width - 1;
  90533. x_step = -1;
  90534. x_end = -1;
  90535. y_start = header.height - 1;
  90536. y_step = -1;
  90537. y_end = -1;
  90538. break;
  90539. }
  90540. // Load the specify method
  90541. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  90542. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  90543. var engine = texture.getEngine();
  90544. engine._uploadDataToTextureDirectly(texture, imageData);
  90545. };
  90546. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90547. var image = pixel_data, colormap = palettes;
  90548. var width = header.width, height = header.height;
  90549. var color, i = 0, x, y;
  90550. var imageData = new Uint8Array(width * height * 4);
  90551. for (y = y_start; y !== y_end; y += y_step) {
  90552. for (x = x_start; x !== x_end; x += x_step, i++) {
  90553. color = image[i];
  90554. imageData[(x + width * y) * 4 + 3] = 255;
  90555. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  90556. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  90557. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  90558. }
  90559. }
  90560. return imageData;
  90561. };
  90562. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90563. var image = pixel_data;
  90564. var width = header.width, height = header.height;
  90565. var color, i = 0, x, y;
  90566. var imageData = new Uint8Array(width * height * 4);
  90567. for (y = y_start; y !== y_end; y += y_step) {
  90568. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90569. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  90570. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  90571. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  90572. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  90573. imageData[(x + width * y) * 4 + 0] = r;
  90574. imageData[(x + width * y) * 4 + 1] = g;
  90575. imageData[(x + width * y) * 4 + 2] = b;
  90576. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  90577. }
  90578. }
  90579. return imageData;
  90580. };
  90581. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90582. var image = pixel_data;
  90583. var width = header.width, height = header.height;
  90584. var i = 0, x, y;
  90585. var imageData = new Uint8Array(width * height * 4);
  90586. for (y = y_start; y !== y_end; y += y_step) {
  90587. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  90588. imageData[(x + width * y) * 4 + 3] = 255;
  90589. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90590. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90591. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90592. }
  90593. }
  90594. return imageData;
  90595. };
  90596. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90597. var image = pixel_data;
  90598. var width = header.width, height = header.height;
  90599. var i = 0, x, y;
  90600. var imageData = new Uint8Array(width * height * 4);
  90601. for (y = y_start; y !== y_end; y += y_step) {
  90602. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  90603. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90604. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90605. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90606. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  90607. }
  90608. }
  90609. return imageData;
  90610. };
  90611. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90612. var image = pixel_data;
  90613. var width = header.width, height = header.height;
  90614. var color, i = 0, x, y;
  90615. var imageData = new Uint8Array(width * height * 4);
  90616. for (y = y_start; y !== y_end; y += y_step) {
  90617. for (x = x_start; x !== x_end; x += x_step, i++) {
  90618. color = image[i];
  90619. imageData[(x + width * y) * 4 + 0] = color;
  90620. imageData[(x + width * y) * 4 + 1] = color;
  90621. imageData[(x + width * y) * 4 + 2] = color;
  90622. imageData[(x + width * y) * 4 + 3] = 255;
  90623. }
  90624. }
  90625. return imageData;
  90626. };
  90627. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90628. var image = pixel_data;
  90629. var width = header.width, height = header.height;
  90630. var i = 0, x, y;
  90631. var imageData = new Uint8Array(width * height * 4);
  90632. for (y = y_start; y !== y_end; y += y_step) {
  90633. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90634. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  90635. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  90636. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90637. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  90638. }
  90639. }
  90640. return imageData;
  90641. };
  90642. //private static _TYPE_NO_DATA = 0;
  90643. TGATools._TYPE_INDEXED = 1;
  90644. TGATools._TYPE_RGB = 2;
  90645. TGATools._TYPE_GREY = 3;
  90646. TGATools._TYPE_RLE_INDEXED = 9;
  90647. TGATools._TYPE_RLE_RGB = 10;
  90648. TGATools._TYPE_RLE_GREY = 11;
  90649. TGATools._ORIGIN_MASK = 0x30;
  90650. TGATools._ORIGIN_SHIFT = 0x04;
  90651. TGATools._ORIGIN_BL = 0x00;
  90652. TGATools._ORIGIN_BR = 0x01;
  90653. TGATools._ORIGIN_UL = 0x02;
  90654. TGATools._ORIGIN_UR = 0x03;
  90655. return TGATools;
  90656. }());
  90657. BABYLON.TGATools = TGATools;
  90658. })(BABYLON || (BABYLON = {}));
  90659. //# sourceMappingURL=babylon.tga.js.map
  90660. var BABYLON;
  90661. (function (BABYLON) {
  90662. /**
  90663. * Implementation of the TGA Texture Loader.
  90664. */
  90665. var TGATextureLoader = /** @class */ (function () {
  90666. function TGATextureLoader() {
  90667. /**
  90668. * Defines wether the loader supports cascade loading the different faces.
  90669. */
  90670. this.supportCascades = false;
  90671. }
  90672. /**
  90673. * This returns if the loader support the current file information.
  90674. * @param extension defines the file extension of the file being loaded
  90675. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90676. * @param fallback defines the fallback internal texture if any
  90677. * @param isBase64 defines whether the texture is encoded as a base64
  90678. * @param isBuffer defines whether the texture data are stored as a buffer
  90679. * @returns true if the loader can load the specified file
  90680. */
  90681. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90682. return extension.indexOf(".tga") === 0;
  90683. };
  90684. /**
  90685. * Transform the url before loading if required.
  90686. * @param rootUrl the url of the texture
  90687. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90688. * @returns the transformed texture
  90689. */
  90690. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90691. return rootUrl;
  90692. };
  90693. /**
  90694. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90695. * @param rootUrl the url of the texture
  90696. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90697. * @returns the fallback texture
  90698. */
  90699. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90700. return null;
  90701. };
  90702. /**
  90703. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90704. * @param data contains the texture data
  90705. * @param texture defines the BabylonJS internal texture
  90706. * @param createPolynomials will be true if polynomials have been requested
  90707. * @param onLoad defines the callback to trigger once the texture is ready
  90708. * @param onError defines the callback to trigger in case of error
  90709. */
  90710. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90711. throw ".env not supported in Cube.";
  90712. };
  90713. /**
  90714. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90715. * @param data contains the texture data
  90716. * @param texture defines the BabylonJS internal texture
  90717. * @param callback defines the method to call once ready to upload
  90718. */
  90719. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90720. var uintData = new Uint8Array(data);
  90721. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90722. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90723. BABYLON.TGATools.UploadContent(texture, uintData);
  90724. });
  90725. };
  90726. return TGATextureLoader;
  90727. }());
  90728. // Register the loader.
  90729. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90730. })(BABYLON || (BABYLON = {}));
  90731. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90732. var BABYLON;
  90733. (function (BABYLON) {
  90734. /**
  90735. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90736. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90737. */
  90738. var KhronosTextureContainer = /** @class */ (function () {
  90739. /**
  90740. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90741. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90742. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90743. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90744. */
  90745. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90746. this.arrayBuffer = arrayBuffer;
  90747. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90748. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90749. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90750. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90751. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90752. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90753. BABYLON.Tools.Error("texture missing KTX identifier");
  90754. return;
  90755. }
  90756. // load the reset of the header in native 32 bit int
  90757. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90758. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90759. var oppositeEndianess = header[0] === 0x01020304;
  90760. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90761. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90762. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90763. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90764. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90765. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90766. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90767. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90768. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90769. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90770. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90771. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90772. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90773. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90774. if (this.glType !== 0) {
  90775. BABYLON.Tools.Error("only compressed formats currently supported");
  90776. return;
  90777. }
  90778. else {
  90779. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  90780. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  90781. }
  90782. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  90783. BABYLON.Tools.Error("only 2D textures currently supported");
  90784. return;
  90785. }
  90786. if (this.numberOfArrayElements !== 0) {
  90787. BABYLON.Tools.Error("texture arrays not currently supported");
  90788. return;
  90789. }
  90790. if (this.numberOfFaces !== facesExpected) {
  90791. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  90792. return;
  90793. }
  90794. // we now have a completely validated file, so could use existence of loadType as success
  90795. // would need to make this more elaborate & adjust checks above to support more than one load type
  90796. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  90797. }
  90798. // not as fast hardware based, but will probably never need to use
  90799. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  90800. return ((val & 0xFF) << 24)
  90801. | ((val & 0xFF00) << 8)
  90802. | ((val >> 8) & 0xFF00)
  90803. | ((val >> 24) & 0xFF);
  90804. };
  90805. /**
  90806. * Uploads KTX content to a Babylon Texture.
  90807. * It is assumed that the texture has already been created & is currently bound
  90808. * @hidden
  90809. */
  90810. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  90811. switch (this.loadType) {
  90812. case KhronosTextureContainer.COMPRESSED_2D:
  90813. this._upload2DCompressedLevels(texture, loadMipmaps);
  90814. break;
  90815. case KhronosTextureContainer.TEX_2D:
  90816. case KhronosTextureContainer.COMPRESSED_3D:
  90817. case KhronosTextureContainer.TEX_3D:
  90818. }
  90819. };
  90820. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  90821. // initialize width & height for level 1
  90822. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  90823. var width = this.pixelWidth;
  90824. var height = this.pixelHeight;
  90825. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  90826. for (var level = 0; level < mipmapCount; level++) {
  90827. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  90828. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  90829. for (var face = 0; face < this.numberOfFaces; face++) {
  90830. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  90831. var engine = texture.getEngine();
  90832. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  90833. dataOffset += imageSize; // add size of the image for the next face/mipmap
  90834. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  90835. }
  90836. width = Math.max(1.0, width * 0.5);
  90837. height = Math.max(1.0, height * 0.5);
  90838. }
  90839. };
  90840. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  90841. // load types
  90842. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  90843. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  90844. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  90845. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  90846. return KhronosTextureContainer;
  90847. }());
  90848. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  90849. })(BABYLON || (BABYLON = {}));
  90850. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  90851. var BABYLON;
  90852. (function (BABYLON) {
  90853. /**
  90854. * Implementation of the KTX Texture Loader.
  90855. */
  90856. var KTXTextureLoader = /** @class */ (function () {
  90857. function KTXTextureLoader() {
  90858. /**
  90859. * Defines wether the loader supports cascade loading the different faces.
  90860. */
  90861. this.supportCascades = false;
  90862. }
  90863. /**
  90864. * This returns if the loader support the current file information.
  90865. * @param extension defines the file extension of the file being loaded
  90866. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90867. * @param fallback defines the fallback internal texture if any
  90868. * @param isBase64 defines whether the texture is encoded as a base64
  90869. * @param isBuffer defines whether the texture data are stored as a buffer
  90870. * @returns true if the loader can load the specified file
  90871. */
  90872. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90873. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  90874. return true;
  90875. }
  90876. return false;
  90877. };
  90878. /**
  90879. * Transform the url before loading if required.
  90880. * @param rootUrl the url of the texture
  90881. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90882. * @returns the transformed texture
  90883. */
  90884. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90885. var lastDot = rootUrl.lastIndexOf('.');
  90886. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  90887. };
  90888. /**
  90889. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90890. * @param rootUrl the url of the texture
  90891. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90892. * @returns the fallback texture
  90893. */
  90894. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90895. // remove the format appended to the rootUrl in the original createCubeTexture call.
  90896. var exp = new RegExp("" + textureFormatInUse + "$");
  90897. return rootUrl.replace(exp, "");
  90898. };
  90899. /**
  90900. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90901. * @param data contains the texture data
  90902. * @param texture defines the BabylonJS internal texture
  90903. * @param createPolynomials will be true if polynomials have been requested
  90904. * @param onLoad defines the callback to trigger once the texture is ready
  90905. * @param onError defines the callback to trigger in case of error
  90906. */
  90907. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90908. if (Array.isArray(data)) {
  90909. return;
  90910. }
  90911. var engine = texture.getEngine();
  90912. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  90913. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  90914. engine._unpackFlipY(true);
  90915. ktx.uploadLevels(texture, texture.generateMipMaps);
  90916. texture.width = ktx.pixelWidth;
  90917. texture.height = ktx.pixelHeight;
  90918. engine._setCubeMapTextureParams(loadMipmap);
  90919. texture.isReady = true;
  90920. };
  90921. /**
  90922. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90923. * @param data contains the texture data
  90924. * @param texture defines the BabylonJS internal texture
  90925. * @param callback defines the method to call once ready to upload
  90926. */
  90927. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90928. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90929. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90930. ktx.uploadLevels(texture, texture.generateMipMaps);
  90931. });
  90932. };
  90933. return KTXTextureLoader;
  90934. }());
  90935. // Register the loader.
  90936. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90937. })(BABYLON || (BABYLON = {}));
  90938. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90939. var BABYLON;
  90940. (function (BABYLON) {
  90941. /**
  90942. * Sets of helpers addressing the serialization and deserialization of environment texture
  90943. * stored in a BabylonJS env file.
  90944. * Those files are usually stored as .env files.
  90945. */
  90946. var EnvironmentTextureTools = /** @class */ (function () {
  90947. function EnvironmentTextureTools() {
  90948. }
  90949. /**
  90950. * Gets the environment info from an env file.
  90951. * @param data The array buffer containing the .env bytes.
  90952. * @returns the environment file info (the json header) if successfully parsed.
  90953. */
  90954. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90955. var dataView = new DataView(data);
  90956. var pos = 0;
  90957. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90958. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90959. BABYLON.Tools.Error('Not a babylon environment map');
  90960. return null;
  90961. }
  90962. }
  90963. // Read json manifest - collect characters up to null terminator
  90964. var manifestString = '';
  90965. var charCode = 0x00;
  90966. while ((charCode = dataView.getUint8(pos++))) {
  90967. manifestString += String.fromCharCode(charCode);
  90968. }
  90969. var manifest = JSON.parse(manifestString);
  90970. if (manifest.specular) {
  90971. // Extend the header with the position of the payload.
  90972. manifest.specular.specularDataPosition = pos;
  90973. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90974. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90975. }
  90976. return manifest;
  90977. };
  90978. /**
  90979. * Creates an environment texture from a loaded cube texture.
  90980. * @param texture defines the cube texture to convert in env file
  90981. * @return a promise containing the environment data if succesfull.
  90982. */
  90983. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90984. var _this = this;
  90985. var internalTexture = texture.getInternalTexture();
  90986. if (!internalTexture) {
  90987. return Promise.reject("The cube texture is invalid.");
  90988. }
  90989. if (!texture._prefiltered) {
  90990. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90991. }
  90992. var engine = internalTexture.getEngine();
  90993. if (engine && engine.premultipliedAlpha) {
  90994. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90995. }
  90996. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90997. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90998. }
  90999. var canvas = engine.getRenderingCanvas();
  91000. if (!canvas) {
  91001. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  91002. }
  91003. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91004. if (!engine.getCaps().textureFloatRender) {
  91005. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91006. if (!engine.getCaps().textureHalfFloatRender) {
  91007. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  91008. }
  91009. }
  91010. var cubeWidth = internalTexture.width;
  91011. var hostingScene = new BABYLON.Scene(engine);
  91012. var specularTextures = {};
  91013. var promises = [];
  91014. // Read and collect all mipmaps data from the cube.
  91015. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  91016. mipmapsCount = Math.round(mipmapsCount);
  91017. var _loop_1 = function (i) {
  91018. var faceWidth = Math.pow(2, mipmapsCount - i);
  91019. var _loop_2 = function (face) {
  91020. var data = texture.readPixels(face, i);
  91021. // Creates a temp texture with the face data.
  91022. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  91023. // And rgbdEncode them.
  91024. var promise = new Promise(function (resolve, reject) {
  91025. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  91026. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91027. rgbdPostProcess.onApply = function (effect) {
  91028. effect._bindTexture("textureSampler", tempTexture);
  91029. };
  91030. // As the process needs to happen on the main canvas, keep track of the current size
  91031. var currentW = engine.getRenderWidth();
  91032. var currentH = engine.getRenderHeight();
  91033. // Set the desired size for the texture
  91034. engine.setSize(faceWidth, faceWidth);
  91035. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  91036. // Reading datas from WebGL
  91037. BABYLON.Tools.ToBlob(canvas, function (blob) {
  91038. var fileReader = new FileReader();
  91039. fileReader.onload = function (event) {
  91040. var arrayBuffer = event.target.result;
  91041. specularTextures[i * 6 + face] = arrayBuffer;
  91042. resolve();
  91043. };
  91044. fileReader.readAsArrayBuffer(blob);
  91045. });
  91046. // Reapply the previous canvas size
  91047. engine.setSize(currentW, currentH);
  91048. });
  91049. });
  91050. promises.push(promise);
  91051. };
  91052. // All faces of the cube.
  91053. for (var face = 0; face < 6; face++) {
  91054. _loop_2(face);
  91055. }
  91056. };
  91057. for (var i = 0; i <= mipmapsCount; i++) {
  91058. _loop_1(i);
  91059. }
  91060. // Once all the textures haves been collected as RGBD stored in PNGs
  91061. return Promise.all(promises).then(function () {
  91062. // We can delete the hosting scene keeping track of all the creation objects
  91063. hostingScene.dispose();
  91064. // Creates the json header for the env texture
  91065. var info = {
  91066. version: 1,
  91067. width: cubeWidth,
  91068. irradiance: _this._CreateEnvTextureIrradiance(texture),
  91069. specular: {
  91070. mipmaps: [],
  91071. lodGenerationScale: texture.lodGenerationScale
  91072. }
  91073. };
  91074. // Sets the specular image data information
  91075. var position = 0;
  91076. for (var i = 0; i <= mipmapsCount; i++) {
  91077. for (var face = 0; face < 6; face++) {
  91078. var byteLength = specularTextures[i * 6 + face].byteLength;
  91079. info.specular.mipmaps.push({
  91080. length: byteLength,
  91081. position: position
  91082. });
  91083. position += byteLength;
  91084. }
  91085. }
  91086. // Encode the JSON as an array buffer
  91087. var infoString = JSON.stringify(info);
  91088. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  91089. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  91090. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  91091. infoView[i] = infoString.charCodeAt(i);
  91092. }
  91093. // Ends up with a null terminator for easier parsing
  91094. infoView[infoString.length] = 0x00;
  91095. // Computes the final required size and creates the storage
  91096. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  91097. var finalBuffer = new ArrayBuffer(totalSize);
  91098. var finalBufferView = new Uint8Array(finalBuffer);
  91099. var dataView = new DataView(finalBuffer);
  91100. // Copy the magic bytes identifying the file in
  91101. var pos = 0;
  91102. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91103. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  91104. }
  91105. // Add the json info
  91106. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  91107. pos += infoBuffer.byteLength;
  91108. // Finally inserts the texture data
  91109. for (var i = 0; i <= mipmapsCount; i++) {
  91110. for (var face = 0; face < 6; face++) {
  91111. var dataBuffer = specularTextures[i * 6 + face];
  91112. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  91113. pos += dataBuffer.byteLength;
  91114. }
  91115. }
  91116. // Voila
  91117. return finalBuffer;
  91118. });
  91119. };
  91120. /**
  91121. * Creates a JSON representation of the spherical data.
  91122. * @param texture defines the texture containing the polynomials
  91123. * @return the JSON representation of the spherical info
  91124. */
  91125. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  91126. var polynmials = texture.sphericalPolynomial;
  91127. if (polynmials == null) {
  91128. return null;
  91129. }
  91130. return {
  91131. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  91132. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  91133. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  91134. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  91135. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  91136. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  91137. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  91138. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  91139. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  91140. };
  91141. };
  91142. /**
  91143. * Uploads the texture info contained in the env file to the GPU.
  91144. * @param texture defines the internal texture to upload to
  91145. * @param arrayBuffer defines the buffer cotaining the data to load
  91146. * @param info defines the texture info retrieved through the GetEnvInfo method
  91147. * @returns a promise
  91148. */
  91149. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  91150. if (info.version !== 1) {
  91151. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  91152. }
  91153. var specularInfo = info.specular;
  91154. if (!specularInfo) {
  91155. // Nothing else parsed so far
  91156. return Promise.resolve();
  91157. }
  91158. // Double checks the enclosed info
  91159. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  91160. mipmapsCount = Math.round(mipmapsCount) + 1;
  91161. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  91162. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  91163. }
  91164. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  91165. var imageData = new Array(mipmapsCount);
  91166. for (var i = 0; i < mipmapsCount; i++) {
  91167. imageData[i] = new Array(6);
  91168. for (var face = 0; face < 6; face++) {
  91169. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  91170. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  91171. }
  91172. }
  91173. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  91174. };
  91175. /**
  91176. * Uploads the levels of image data to the GPU.
  91177. * @param texture defines the internal texture to upload to
  91178. * @param imageData defines the array buffer views of image data [mipmap][face]
  91179. * @returns a promise
  91180. */
  91181. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  91182. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  91183. throw new Error("Texture size must be a power of two");
  91184. }
  91185. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  91186. // Gets everything ready.
  91187. var engine = texture.getEngine();
  91188. var expandTexture = false;
  91189. var generateNonLODTextures = false;
  91190. var rgbdPostProcess = null;
  91191. var cubeRtt = null;
  91192. var lodTextures = null;
  91193. var caps = engine.getCaps();
  91194. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91195. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91196. texture.generateMipMaps = true;
  91197. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  91198. // Add extra process if texture lod is not supported
  91199. if (!caps.textureLOD) {
  91200. expandTexture = false;
  91201. generateNonLODTextures = true;
  91202. lodTextures = {};
  91203. }
  91204. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  91205. else if (engine.webGLVersion < 2) {
  91206. expandTexture = false;
  91207. }
  91208. // If half float available we can uncompress the texture
  91209. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  91210. expandTexture = true;
  91211. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91212. }
  91213. // If full float available we can uncompress the texture
  91214. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  91215. expandTexture = true;
  91216. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91217. }
  91218. // Expand the texture if possible
  91219. if (expandTexture) {
  91220. // Simply run through the decode PP
  91221. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  91222. texture._isRGBD = false;
  91223. texture.invertY = false;
  91224. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  91225. generateDepthBuffer: false,
  91226. generateMipMaps: true,
  91227. generateStencilBuffer: false,
  91228. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  91229. type: texture.type,
  91230. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  91231. });
  91232. }
  91233. else {
  91234. texture._isRGBD = true;
  91235. texture.invertY = true;
  91236. // In case of missing support, applies the same patch than DDS files.
  91237. if (generateNonLODTextures) {
  91238. var mipSlices = 3;
  91239. var scale = texture._lodGenerationScale;
  91240. var offset = texture._lodGenerationOffset;
  91241. for (var i = 0; i < mipSlices; i++) {
  91242. //compute LOD from even spacing in smoothness (matching shader calculation)
  91243. var smoothness = i / (mipSlices - 1);
  91244. var roughness = 1 - smoothness;
  91245. var minLODIndex = offset; // roughness = 0
  91246. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  91247. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  91248. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  91249. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  91250. glTextureFromLod.isCube = true;
  91251. glTextureFromLod.invertY = true;
  91252. glTextureFromLod.generateMipMaps = false;
  91253. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  91254. // Wrap in a base texture for easy binding.
  91255. var lodTexture = new BABYLON.BaseTexture(null);
  91256. lodTexture.isCube = true;
  91257. lodTexture._texture = glTextureFromLod;
  91258. lodTextures[mipmapIndex] = lodTexture;
  91259. switch (i) {
  91260. case 0:
  91261. texture._lodTextureLow = lodTexture;
  91262. break;
  91263. case 1:
  91264. texture._lodTextureMid = lodTexture;
  91265. break;
  91266. case 2:
  91267. texture._lodTextureHigh = lodTexture;
  91268. break;
  91269. }
  91270. }
  91271. }
  91272. }
  91273. var promises = [];
  91274. var _loop_3 = function (i) {
  91275. var _loop_4 = function (face) {
  91276. // Constructs an image element from image data
  91277. var bytes = imageData[i][face];
  91278. var blob = new Blob([bytes], { type: 'image/png' });
  91279. var url = URL.createObjectURL(blob);
  91280. var image = new Image();
  91281. image.src = url;
  91282. // Enqueue promise to upload to the texture.
  91283. var promise = new Promise(function (resolve, reject) {
  91284. image.onload = function () {
  91285. if (expandTexture) {
  91286. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  91287. reject(message);
  91288. }, image);
  91289. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91290. // Uncompress the data to a RTT
  91291. rgbdPostProcess.onApply = function (effect) {
  91292. effect._bindTexture("textureSampler", tempTexture_1);
  91293. effect.setFloat2("scale", 1, 1);
  91294. };
  91295. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  91296. // Cleanup
  91297. engine.restoreDefaultFramebuffer();
  91298. tempTexture_1.dispose();
  91299. window.URL.revokeObjectURL(url);
  91300. resolve();
  91301. });
  91302. }
  91303. else {
  91304. engine._uploadImageToTexture(texture, image, face, i);
  91305. // Upload the face to the non lod texture support
  91306. if (generateNonLODTextures) {
  91307. var lodTexture = lodTextures[i];
  91308. if (lodTexture) {
  91309. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  91310. }
  91311. }
  91312. resolve();
  91313. }
  91314. };
  91315. image.onerror = function (error) {
  91316. reject(error);
  91317. };
  91318. });
  91319. promises.push(promise);
  91320. };
  91321. // All faces
  91322. for (var face = 0; face < 6; face++) {
  91323. _loop_4(face);
  91324. }
  91325. };
  91326. // All mipmaps up to provided number of images
  91327. for (var i = 0; i < imageData.length; i++) {
  91328. _loop_3(i);
  91329. }
  91330. // Fill remaining mipmaps with black textures.
  91331. if (imageData.length < mipmapsCount) {
  91332. var data = void 0;
  91333. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  91334. var dataLength = size * size * 4;
  91335. switch (texture.type) {
  91336. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  91337. data = new Uint8Array(dataLength);
  91338. break;
  91339. }
  91340. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  91341. data = new Uint16Array(dataLength);
  91342. break;
  91343. }
  91344. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  91345. data = new Float32Array(dataLength);
  91346. break;
  91347. }
  91348. }
  91349. for (var i = imageData.length; i < mipmapsCount; i++) {
  91350. for (var face = 0; face < 6; face++) {
  91351. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  91352. }
  91353. }
  91354. }
  91355. // Once all done, finishes the cleanup and return
  91356. return Promise.all(promises).then(function () {
  91357. // Release temp RTT.
  91358. if (cubeRtt) {
  91359. engine._releaseFramebufferObjects(cubeRtt);
  91360. cubeRtt._swapAndDie(texture);
  91361. }
  91362. // Release temp Post Process.
  91363. if (rgbdPostProcess) {
  91364. rgbdPostProcess.dispose();
  91365. }
  91366. // Flag internal texture as ready in case they are in use.
  91367. if (generateNonLODTextures) {
  91368. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  91369. texture._lodTextureHigh._texture.isReady = true;
  91370. }
  91371. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  91372. texture._lodTextureMid._texture.isReady = true;
  91373. }
  91374. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  91375. texture._lodTextureLow._texture.isReady = true;
  91376. }
  91377. }
  91378. });
  91379. };
  91380. /**
  91381. * Uploads spherical polynomials information to the texture.
  91382. * @param texture defines the texture we are trying to upload the information to
  91383. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  91384. */
  91385. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  91386. if (info.version !== 1) {
  91387. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  91388. }
  91389. var irradianceInfo = info.irradiance;
  91390. if (!irradianceInfo) {
  91391. return;
  91392. }
  91393. var sp = new BABYLON.SphericalPolynomial();
  91394. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  91395. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  91396. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  91397. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  91398. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  91399. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  91400. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  91401. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  91402. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  91403. texture._sphericalPolynomial = sp;
  91404. };
  91405. /**
  91406. * Magic number identifying the env file.
  91407. */
  91408. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  91409. return EnvironmentTextureTools;
  91410. }());
  91411. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  91412. })(BABYLON || (BABYLON = {}));
  91413. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  91414. var BABYLON;
  91415. (function (BABYLON) {
  91416. /**
  91417. * Implementation of the ENV Texture Loader.
  91418. */
  91419. var ENVTextureLoader = /** @class */ (function () {
  91420. function ENVTextureLoader() {
  91421. /**
  91422. * Defines wether the loader supports cascade loading the different faces.
  91423. */
  91424. this.supportCascades = false;
  91425. }
  91426. /**
  91427. * This returns if the loader support the current file information.
  91428. * @param extension defines the file extension of the file being loaded
  91429. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91430. * @param fallback defines the fallback internal texture if any
  91431. * @param isBase64 defines whether the texture is encoded as a base64
  91432. * @param isBuffer defines whether the texture data are stored as a buffer
  91433. * @returns true if the loader can load the specified file
  91434. */
  91435. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91436. return extension.indexOf(".env") === 0;
  91437. };
  91438. /**
  91439. * Transform the url before loading if required.
  91440. * @param rootUrl the url of the texture
  91441. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91442. * @returns the transformed texture
  91443. */
  91444. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91445. return rootUrl;
  91446. };
  91447. /**
  91448. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91449. * @param rootUrl the url of the texture
  91450. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91451. * @returns the fallback texture
  91452. */
  91453. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91454. return null;
  91455. };
  91456. /**
  91457. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91458. * @param data contains the texture data
  91459. * @param texture defines the BabylonJS internal texture
  91460. * @param createPolynomials will be true if polynomials have been requested
  91461. * @param onLoad defines the callback to trigger once the texture is ready
  91462. * @param onError defines the callback to trigger in case of error
  91463. */
  91464. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91465. if (Array.isArray(data)) {
  91466. return;
  91467. }
  91468. data = data;
  91469. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  91470. if (info) {
  91471. texture.width = info.width;
  91472. texture.height = info.width;
  91473. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  91474. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  91475. texture.isReady = true;
  91476. if (onLoad) {
  91477. onLoad();
  91478. }
  91479. });
  91480. }
  91481. else if (onError) {
  91482. onError("Can not parse the environment file", null);
  91483. }
  91484. };
  91485. /**
  91486. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91487. * @param data contains the texture data
  91488. * @param texture defines the BabylonJS internal texture
  91489. * @param callback defines the method to call once ready to upload
  91490. */
  91491. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  91492. throw ".env not supported in 2d.";
  91493. };
  91494. return ENVTextureLoader;
  91495. }());
  91496. // Register the loader.
  91497. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  91498. })(BABYLON || (BABYLON = {}));
  91499. //# sourceMappingURL=babylon.envTextureLoader.js.map
  91500. var BABYLON;
  91501. (function (BABYLON) {
  91502. /**
  91503. * Renders a layer on top of an existing scene
  91504. */
  91505. var UtilityLayerRenderer = /** @class */ (function () {
  91506. /**
  91507. * Instantiates a UtilityLayerRenderer
  91508. * @param originalScene the original scene that will be rendered on top of
  91509. */
  91510. function UtilityLayerRenderer(
  91511. /** the original scene that will be rendered on top of */
  91512. originalScene) {
  91513. var _this = this;
  91514. this.originalScene = originalScene;
  91515. this._pointerCaptures = {};
  91516. this._lastPointerEvents = {};
  91517. /**
  91518. * If the utility layer should automatically be rendered on top of existing scene
  91519. */
  91520. this.shouldRender = true;
  91521. /**
  91522. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  91523. */
  91524. this.onlyCheckPointerDownEvents = true;
  91525. /**
  91526. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  91527. */
  91528. this.processAllEvents = false;
  91529. /**
  91530. * Observable raised when the pointer move from the utility layer scene to the main scene
  91531. */
  91532. this.onPointerOutObservable = new BABYLON.Observable();
  91533. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  91534. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  91535. this.utilityLayerScene._allowPostProcessClearColor = false;
  91536. originalScene.getEngine().scenes.pop();
  91537. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  91538. this.utilityLayerScene.detachControl();
  91539. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  91540. if (!_this.processAllEvents) {
  91541. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  91542. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  91543. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  91544. return;
  91545. }
  91546. }
  91547. var pointerEvent = (prePointerInfo.event);
  91548. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  91549. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91550. return;
  91551. }
  91552. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  91553. if (!prePointerInfo.ray && utilityScenePick) {
  91554. prePointerInfo.ray = utilityScenePick.ray;
  91555. }
  91556. // always fire the prepointer oversvable
  91557. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  91558. // allow every non pointer down event to flow to the utility layer
  91559. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  91560. if (!prePointerInfo.skipOnPointerObservable) {
  91561. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91562. }
  91563. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  91564. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91565. }
  91566. return;
  91567. }
  91568. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  91569. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  91570. if (utilityScenePick && utilityScenePick.hit) {
  91571. if (!prePointerInfo.skipOnPointerObservable) {
  91572. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91573. }
  91574. prePointerInfo.skipOnPointerObservable = true;
  91575. }
  91576. }
  91577. else {
  91578. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  91579. var pointerEvent_1 = (prePointerInfo.event);
  91580. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  91581. if (originalScenePick && utilityScenePick) {
  91582. // No pick in utility scene
  91583. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  91584. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91585. // We touched an utility mesh present in the main scene
  91586. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91587. prePointerInfo.skipOnPointerObservable = true;
  91588. }
  91589. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91590. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  91591. }
  91592. }
  91593. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  91594. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  91595. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  91596. // If a previous utility layer set this, do not unset this
  91597. if (!prePointerInfo.skipOnPointerObservable) {
  91598. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  91599. }
  91600. }
  91601. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  91602. // We have a pick in both scenes but main is closer than utility
  91603. // We touched an utility mesh present in the main scene
  91604. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91605. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91606. prePointerInfo.skipOnPointerObservable = true;
  91607. }
  91608. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  91609. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  91610. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  91611. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  91612. }
  91613. }
  91614. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  91615. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  91616. }
  91617. }
  91618. }
  91619. });
  91620. // Render directly on top of existing scene without clearing
  91621. this.utilityLayerScene.autoClear = false;
  91622. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  91623. if (_this.shouldRender) {
  91624. _this.render();
  91625. }
  91626. });
  91627. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  91628. _this.dispose();
  91629. });
  91630. this._updateCamera();
  91631. }
  91632. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  91633. /**
  91634. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  91635. */
  91636. get: function () {
  91637. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  91638. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91639. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91640. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91641. });
  91642. }
  91643. return UtilityLayerRenderer._DefaultUtilityLayer;
  91644. },
  91645. enumerable: true,
  91646. configurable: true
  91647. });
  91648. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  91649. /**
  91650. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  91651. */
  91652. get: function () {
  91653. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  91654. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91655. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  91656. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91657. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91658. });
  91659. }
  91660. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  91661. },
  91662. enumerable: true,
  91663. configurable: true
  91664. });
  91665. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  91666. if (!prePointerInfo.skipOnPointerObservable) {
  91667. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  91668. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  91669. }
  91670. };
  91671. /**
  91672. * Renders the utility layers scene on top of the original scene
  91673. */
  91674. UtilityLayerRenderer.prototype.render = function () {
  91675. this._updateCamera();
  91676. if (this.utilityLayerScene.activeCamera) {
  91677. // Set the camera's scene to utility layers scene
  91678. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  91679. var camera = this.utilityLayerScene.activeCamera;
  91680. camera._scene = this.utilityLayerScene;
  91681. if (camera.leftCamera) {
  91682. camera.leftCamera._scene = this.utilityLayerScene;
  91683. }
  91684. if (camera.rightCamera) {
  91685. camera.rightCamera._scene = this.utilityLayerScene;
  91686. }
  91687. this.utilityLayerScene.render(false);
  91688. // Reset camera's scene back to original
  91689. camera._scene = oldScene;
  91690. if (camera.leftCamera) {
  91691. camera.leftCamera._scene = oldScene;
  91692. }
  91693. if (camera.rightCamera) {
  91694. camera.rightCamera._scene = oldScene;
  91695. }
  91696. }
  91697. };
  91698. /**
  91699. * Disposes of the renderer
  91700. */
  91701. UtilityLayerRenderer.prototype.dispose = function () {
  91702. this.onPointerOutObservable.clear();
  91703. if (this._afterRenderObserver) {
  91704. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91705. }
  91706. if (this._sceneDisposeObserver) {
  91707. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91708. }
  91709. if (this._originalPointerObserver) {
  91710. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91711. }
  91712. this.utilityLayerScene.dispose();
  91713. };
  91714. UtilityLayerRenderer.prototype._updateCamera = function () {
  91715. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91716. };
  91717. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91718. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91719. return UtilityLayerRenderer;
  91720. }());
  91721. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91722. })(BABYLON || (BABYLON = {}));
  91723. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91724. //# sourceMappingURL=babylon.behavior.js.map
  91725. var BABYLON;
  91726. (function (BABYLON) {
  91727. /**
  91728. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91729. */
  91730. var PointerDragBehavior = /** @class */ (function () {
  91731. /**
  91732. * Creates a pointer drag behavior that can be attached to a mesh
  91733. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  91734. */
  91735. function PointerDragBehavior(options) {
  91736. /**
  91737. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  91738. */
  91739. this.maxDragAngle = 0;
  91740. /**
  91741. * @hidden
  91742. */
  91743. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91744. /**
  91745. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91746. */
  91747. this.currentDraggingPointerID = -1;
  91748. /**
  91749. * If the behavior is currently in a dragging state
  91750. */
  91751. this.dragging = false;
  91752. /**
  91753. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  91754. */
  91755. this.dragDeltaRatio = 0.2;
  91756. /**
  91757. * If the drag plane orientation should be updated during the dragging (Default: true)
  91758. */
  91759. this.updateDragPlane = true;
  91760. // Debug mode will display drag planes to help visualize behavior
  91761. this._debugMode = false;
  91762. this._moving = false;
  91763. /**
  91764. * Fires each time the attached mesh is dragged with the pointer
  91765. * * delta between last drag position and current drag position in world space
  91766. * * dragDistance along the drag axis
  91767. * * dragPlaneNormal normal of the current drag plane used during the drag
  91768. * * dragPlanePoint in world space where the drag intersects the drag plane
  91769. */
  91770. this.onDragObservable = new BABYLON.Observable();
  91771. /**
  91772. * Fires each time a drag begins (eg. mouse down on mesh)
  91773. */
  91774. this.onDragStartObservable = new BABYLON.Observable();
  91775. /**
  91776. * Fires each time a drag ends (eg. mouse release after drag)
  91777. */
  91778. this.onDragEndObservable = new BABYLON.Observable();
  91779. /**
  91780. * If the attached mesh should be moved when dragged
  91781. */
  91782. this.moveAttached = true;
  91783. /**
  91784. * If the drag behavior will react to drag events (Default: true)
  91785. */
  91786. this.enabled = true;
  91787. /**
  91788. * If camera controls should be detached during the drag
  91789. */
  91790. this.detachCameraControls = true;
  91791. /**
  91792. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  91793. */
  91794. this.useObjectOrienationForDragging = true;
  91795. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91796. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  91797. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  91798. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91799. this._attachedElement = null;
  91800. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91801. this._lastPointerRay = {};
  91802. this._dragDelta = new BABYLON.Vector3();
  91803. // Variables to avoid instantiation in the below method
  91804. this._pointA = new BABYLON.Vector3(0, 0, 0);
  91805. this._pointB = new BABYLON.Vector3(0, 0, 0);
  91806. this._pointC = new BABYLON.Vector3(0, 0, 0);
  91807. this._lineA = new BABYLON.Vector3(0, 0, 0);
  91808. this._lineB = new BABYLON.Vector3(0, 0, 0);
  91809. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  91810. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  91811. this._options = options ? options : {};
  91812. var optionCount = 0;
  91813. if (this._options.dragAxis) {
  91814. optionCount++;
  91815. }
  91816. if (this._options.dragPlaneNormal) {
  91817. optionCount++;
  91818. }
  91819. if (optionCount > 1) {
  91820. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  91821. }
  91822. }
  91823. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  91824. /**
  91825. * The name of the behavior
  91826. */
  91827. get: function () {
  91828. return "PointerDrag";
  91829. },
  91830. enumerable: true,
  91831. configurable: true
  91832. });
  91833. /**
  91834. * Initializes the behavior
  91835. */
  91836. PointerDragBehavior.prototype.init = function () { };
  91837. /**
  91838. * Attaches the drag behavior the passed in mesh
  91839. * @param ownerNode The mesh that will be dragged around once attached
  91840. */
  91841. PointerDragBehavior.prototype.attach = function (ownerNode) {
  91842. var _this = this;
  91843. this._scene = ownerNode.getScene();
  91844. this._attachedNode = ownerNode;
  91845. // Initialize drag plane to not interfere with existing scene
  91846. if (!PointerDragBehavior._planeScene) {
  91847. if (this._debugMode) {
  91848. PointerDragBehavior._planeScene = this._scene;
  91849. }
  91850. else {
  91851. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  91852. PointerDragBehavior._planeScene.detachControl();
  91853. this._scene.getEngine().scenes.pop();
  91854. this._scene.onDisposeObservable.addOnce(function () {
  91855. PointerDragBehavior._planeScene.dispose();
  91856. PointerDragBehavior._planeScene = null;
  91857. });
  91858. }
  91859. }
  91860. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  91861. // State of the drag
  91862. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  91863. var pickPredicate = function (m) {
  91864. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  91865. };
  91866. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91867. if (!_this.enabled) {
  91868. return;
  91869. }
  91870. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91871. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91872. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  91873. }
  91874. }
  91875. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91876. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91877. _this.releaseDrag();
  91878. }
  91879. }
  91880. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91881. var pointerId = pointerInfo.event.pointerId;
  91882. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  91883. if (!_this._lastPointerRay[pointerId]) {
  91884. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91885. }
  91886. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  91887. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  91888. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  91889. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  91890. _this._moveDrag(pointerInfo.pickInfo.ray);
  91891. }
  91892. }
  91893. }
  91894. });
  91895. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91896. if (_this._moving && _this.moveAttached) {
  91897. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  91898. // Slowly move mesh to avoid jitter
  91899. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  91900. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91901. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91902. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  91903. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  91904. }
  91905. });
  91906. };
  91907. PointerDragBehavior.prototype.releaseDrag = function () {
  91908. this.dragging = false;
  91909. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91910. this.currentDraggingPointerID = -1;
  91911. this._moving = false;
  91912. // Reattach camera controls
  91913. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91914. this._scene.activeCamera.attachControl(this._attachedElement, true);
  91915. }
  91916. };
  91917. /**
  91918. * Simulates the start of a pointer drag event on the behavior
  91919. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  91920. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  91921. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  91922. */
  91923. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  91924. if (pointerId === void 0) { pointerId = 1; }
  91925. this._startDrag(pointerId, fromRay, startPickedPoint);
  91926. if (this._lastPointerRay[pointerId]) {
  91927. // if there was a last pointer ray drag the object there
  91928. this._moveDrag(this._lastPointerRay[pointerId]);
  91929. }
  91930. };
  91931. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  91932. if (pointerId === void 0) { pointerId = 1; }
  91933. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  91934. return;
  91935. }
  91936. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  91937. // Create start ray from the camera to the object
  91938. if (fromRay) {
  91939. this._startDragRay.direction.copyFrom(fromRay.direction);
  91940. this._startDragRay.origin.copyFrom(fromRay.origin);
  91941. }
  91942. else {
  91943. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  91944. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  91945. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  91946. }
  91947. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  91948. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  91949. if (pickedPoint) {
  91950. this.dragging = true;
  91951. this.currentDraggingPointerID = 1;
  91952. this.lastDragPosition.copyFrom(pickedPoint);
  91953. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  91954. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  91955. // Detatch camera controls
  91956. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91957. if (this._scene.activeCamera.inputs.attachedElement) {
  91958. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  91959. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  91960. }
  91961. else {
  91962. this._attachedElement = null;
  91963. }
  91964. }
  91965. }
  91966. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  91967. };
  91968. PointerDragBehavior.prototype._moveDrag = function (ray) {
  91969. this._moving = true;
  91970. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  91971. if (pickedPoint) {
  91972. if (this.updateDragPlane) {
  91973. this._updateDragPlanePosition(ray, pickedPoint);
  91974. }
  91975. var dragLength = 0;
  91976. // depending on the drag mode option drag accordingly
  91977. if (this._options.dragAxis) {
  91978. // Convert local drag axis to world
  91979. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  91980. // Project delta drag from the drag plane onto the drag axis
  91981. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  91982. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  91983. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  91984. }
  91985. else {
  91986. dragLength = this._dragDelta.length();
  91987. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  91988. }
  91989. this._targetPosition.addInPlace(this._dragDelta);
  91990. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  91991. this.lastDragPosition.copyFrom(pickedPoint);
  91992. }
  91993. };
  91994. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91995. var _this = this;
  91996. if (!ray) {
  91997. return null;
  91998. }
  91999. // Calculate angle between plane normal and ray
  92000. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  92001. // Correct if ray is casted from oposite side
  92002. if (angle > Math.PI / 2) {
  92003. angle = Math.PI - angle;
  92004. }
  92005. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  92006. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  92007. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  92008. // Invert ray direction along the towards object axis
  92009. this._tmpVector.copyFrom(ray.direction);
  92010. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  92011. this._alternatePickedPoint.normalize();
  92012. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  92013. this._tmpVector.addInPlace(this._alternatePickedPoint);
  92014. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  92015. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  92016. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  92017. this._alternatePickedPoint.addInPlace(this._tmpVector);
  92018. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  92019. return this._alternatePickedPoint;
  92020. }
  92021. else {
  92022. return null;
  92023. }
  92024. }
  92025. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  92026. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  92027. return pickResult.pickedPoint;
  92028. }
  92029. else {
  92030. return null;
  92031. }
  92032. };
  92033. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  92034. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  92035. this._pointA.copyFrom(dragPlanePosition);
  92036. if (this._options.dragAxis) {
  92037. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  92038. // Calculate plane normal in direction of camera but perpendicular to drag axis
  92039. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  92040. ray.origin.subtractToRef(this._pointA, this._pointC);
  92041. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  92042. // Get perpendicular line from direction to camera and drag axis
  92043. this._pointB.subtractToRef(this._pointA, this._lineA);
  92044. this._pointC.subtractToRef(this._pointA, this._lineB);
  92045. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  92046. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  92047. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  92048. this._lookAt.normalize();
  92049. this._dragPlane.position.copyFrom(this._pointA);
  92050. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  92051. this._dragPlane.lookAt(this._lookAt);
  92052. }
  92053. else if (this._options.dragPlaneNormal) {
  92054. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  92055. this._dragPlane.position.copyFrom(this._pointA);
  92056. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  92057. this._dragPlane.lookAt(this._lookAt);
  92058. }
  92059. else {
  92060. this._dragPlane.position.copyFrom(this._pointA);
  92061. this._dragPlane.lookAt(ray.origin);
  92062. }
  92063. this._dragPlane.computeWorldMatrix(true);
  92064. };
  92065. /**
  92066. * Detaches the behavior from the mesh
  92067. */
  92068. PointerDragBehavior.prototype.detach = function () {
  92069. if (this._pointerObserver) {
  92070. this._scene.onPointerObservable.remove(this._pointerObserver);
  92071. }
  92072. if (this._beforeRenderObserver) {
  92073. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92074. }
  92075. };
  92076. return PointerDragBehavior;
  92077. }());
  92078. BABYLON.PointerDragBehavior = PointerDragBehavior;
  92079. })(BABYLON || (BABYLON = {}));
  92080. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  92081. var BABYLON;
  92082. (function (BABYLON) {
  92083. /**
  92084. * A behavior that when attached to a mesh will allow the mesh to be scaled
  92085. */
  92086. var MultiPointerScaleBehavior = /** @class */ (function () {
  92087. function MultiPointerScaleBehavior() {
  92088. this._startDistance = 0;
  92089. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  92090. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  92091. this._sceneRenderObserver = null;
  92092. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  92093. this._dragBehaviorA.moveAttached = false;
  92094. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  92095. this._dragBehaviorB.moveAttached = false;
  92096. }
  92097. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  92098. /**
  92099. * The name of the behavior
  92100. */
  92101. get: function () {
  92102. return "MultiPointerScale";
  92103. },
  92104. enumerable: true,
  92105. configurable: true
  92106. });
  92107. /**
  92108. * Initializes the behavior
  92109. */
  92110. MultiPointerScaleBehavior.prototype.init = function () { };
  92111. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  92112. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  92113. };
  92114. /**
  92115. * Attaches the scale behavior the passed in mesh
  92116. * @param ownerNode The mesh that will be scaled around once attached
  92117. */
  92118. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  92119. var _this = this;
  92120. this._ownerNode = ownerNode;
  92121. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  92122. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  92123. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92124. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92125. _this._dragBehaviorA.releaseDrag();
  92126. }
  92127. else {
  92128. _this._initialScale.copyFrom(ownerNode.scaling);
  92129. _this._startDistance = _this._getCurrentDistance();
  92130. }
  92131. }
  92132. });
  92133. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  92134. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92135. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92136. _this._dragBehaviorB.releaseDrag();
  92137. }
  92138. else {
  92139. _this._initialScale.copyFrom(ownerNode.scaling);
  92140. _this._startDistance = _this._getCurrentDistance();
  92141. }
  92142. }
  92143. });
  92144. // Once both drag behaviors are active scale based on the distance between the two pointers
  92145. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92146. behavior.onDragObservable.add(function () {
  92147. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92148. var ratio = _this._getCurrentDistance() / _this._startDistance;
  92149. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  92150. }
  92151. });
  92152. });
  92153. ownerNode.addBehavior(this._dragBehaviorA);
  92154. ownerNode.addBehavior(this._dragBehaviorB);
  92155. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92156. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92157. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92158. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  92159. if (change.length() > 0.01) {
  92160. ownerNode.scaling.addInPlace(change);
  92161. }
  92162. }
  92163. });
  92164. };
  92165. /**
  92166. * Detaches the behavior from the mesh
  92167. */
  92168. MultiPointerScaleBehavior.prototype.detach = function () {
  92169. var _this = this;
  92170. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92171. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92172. behavior.onDragStartObservable.clear();
  92173. behavior.onDragObservable.clear();
  92174. _this._ownerNode.removeBehavior(behavior);
  92175. });
  92176. };
  92177. return MultiPointerScaleBehavior;
  92178. }());
  92179. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  92180. })(BABYLON || (BABYLON = {}));
  92181. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  92182. var BABYLON;
  92183. (function (BABYLON) {
  92184. /**
  92185. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  92186. */
  92187. var SixDofDragBehavior = /** @class */ (function () {
  92188. function SixDofDragBehavior() {
  92189. this._sceneRenderObserver = null;
  92190. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92191. this._moving = false;
  92192. this._startingOrientation = new BABYLON.Quaternion();
  92193. /**
  92194. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  92195. */
  92196. this.zDragFactor = 3;
  92197. /**
  92198. * If the behavior is currently in a dragging state
  92199. */
  92200. this.dragging = false;
  92201. /**
  92202. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  92203. */
  92204. this.dragDeltaRatio = 0.2;
  92205. /**
  92206. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92207. */
  92208. this.currentDraggingPointerID = -1;
  92209. /**
  92210. * If camera controls should be detached during the drag
  92211. */
  92212. this.detachCameraControls = true;
  92213. }
  92214. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  92215. /**
  92216. * The name of the behavior
  92217. */
  92218. get: function () {
  92219. return "SixDofDrag";
  92220. },
  92221. enumerable: true,
  92222. configurable: true
  92223. });
  92224. /**
  92225. * Initializes the behavior
  92226. */
  92227. SixDofDragBehavior.prototype.init = function () { };
  92228. /**
  92229. * Attaches the scale behavior the passed in mesh
  92230. * @param ownerNode The mesh that will be scaled around once attached
  92231. */
  92232. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  92233. var _this = this;
  92234. this._ownerNode = ownerNode;
  92235. this._scene = this._ownerNode.getScene();
  92236. if (!SixDofDragBehavior._virtualScene) {
  92237. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  92238. this._scene.getEngine().scenes.pop();
  92239. }
  92240. var pickedMesh = null;
  92241. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  92242. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  92243. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92244. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  92245. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92246. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  92247. var pickPredicate = function (m) {
  92248. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  92249. };
  92250. var attachedElement = null;
  92251. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92252. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92253. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92254. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92255. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92256. }
  92257. pickedMesh = _this._ownerNode;
  92258. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92259. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92260. // Set position and orientation of the controller
  92261. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  92262. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  92263. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  92264. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92265. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  92266. if (!pickedMesh.rotationQuaternion) {
  92267. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  92268. }
  92269. var oldParent = pickedMesh.parent;
  92270. pickedMesh.setParent(null);
  92271. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  92272. pickedMesh.setParent(oldParent);
  92273. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92274. // Update state
  92275. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  92276. _this.dragging = true;
  92277. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  92278. // Detatch camera controls
  92279. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92280. if (_this._scene.activeCamera.inputs.attachedElement) {
  92281. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  92282. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  92283. }
  92284. else {
  92285. attachedElement = null;
  92286. }
  92287. }
  92288. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  92289. }
  92290. }
  92291. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92292. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92293. _this.dragging = false;
  92294. _this._moving = false;
  92295. _this.currentDraggingPointerID = -1;
  92296. pickedMesh = null;
  92297. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92298. // Reattach camera controls
  92299. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92300. _this._scene.activeCamera.attachControl(attachedElement, true);
  92301. }
  92302. }
  92303. }
  92304. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92305. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  92306. var zDragFactor = _this.zDragFactor;
  92307. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92308. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92309. zDragFactor = 0;
  92310. }
  92311. // Calculate controller drag distance in controller space
  92312. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  92313. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92314. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  92315. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92316. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  92317. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  92318. if (_this._virtualDragMesh.position.z < 0) {
  92319. _this._virtualDragMesh.position.z = 0;
  92320. }
  92321. // Update the controller position
  92322. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  92323. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  92324. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92325. // Move the virtualObjectsPosition into the picked mesh's space if needed
  92326. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  92327. if (pickedMesh.parent) {
  92328. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  92329. }
  92330. if (!_this._moving) {
  92331. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  92332. }
  92333. _this._moving = true;
  92334. }
  92335. }
  92336. });
  92337. var tmpQuaternion = new BABYLON.Quaternion();
  92338. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92339. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92340. if (_this.dragging && _this._moving && pickedMesh) {
  92341. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92342. // Slowly move mesh to avoid jitter
  92343. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  92344. // Get change in rotation
  92345. tmpQuaternion.copyFrom(_this._startingOrientation);
  92346. tmpQuaternion.x = -tmpQuaternion.x;
  92347. tmpQuaternion.y = -tmpQuaternion.y;
  92348. tmpQuaternion.z = -tmpQuaternion.z;
  92349. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  92350. // Convert change in rotation to only y axis rotation
  92351. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  92352. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  92353. // Slowly move mesh to avoid jitter
  92354. var oldParent = pickedMesh.parent;
  92355. pickedMesh.setParent(null);
  92356. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  92357. pickedMesh.setParent(oldParent);
  92358. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  92359. }
  92360. });
  92361. };
  92362. /**
  92363. * Detaches the behavior from the mesh
  92364. */
  92365. SixDofDragBehavior.prototype.detach = function () {
  92366. if (this._scene) {
  92367. this._scene.onPointerObservable.remove(this._pointerObserver);
  92368. }
  92369. if (this._ownerNode) {
  92370. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92371. }
  92372. if (this._virtualOriginMesh) {
  92373. this._virtualOriginMesh.dispose();
  92374. }
  92375. if (this._virtualDragMesh) {
  92376. this._virtualDragMesh.dispose();
  92377. }
  92378. };
  92379. return SixDofDragBehavior;
  92380. }());
  92381. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  92382. })(BABYLON || (BABYLON = {}));
  92383. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  92384. var BABYLON;
  92385. (function (BABYLON) {
  92386. /**
  92387. * @hidden
  92388. */
  92389. var FaceDirectionInfo = /** @class */ (function () {
  92390. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  92391. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  92392. if (diff === void 0) { diff = 0; }
  92393. if (ignore === void 0) { ignore = false; }
  92394. this.direction = direction;
  92395. this.rotatedDirection = rotatedDirection;
  92396. this.diff = diff;
  92397. this.ignore = ignore;
  92398. }
  92399. return FaceDirectionInfo;
  92400. }());
  92401. /**
  92402. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  92403. */
  92404. var AttachToBoxBehavior = /** @class */ (function () {
  92405. /**
  92406. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  92407. * @param ui The transform node that should be attched to the mesh
  92408. */
  92409. function AttachToBoxBehavior(ui) {
  92410. this.ui = ui;
  92411. /**
  92412. * The name of the behavior
  92413. */
  92414. this.name = "AttachToBoxBehavior";
  92415. /**
  92416. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  92417. */
  92418. this.distanceAwayFromFace = 0.15;
  92419. /**
  92420. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  92421. */
  92422. this.distanceAwayFromBottomOfFace = 0.15;
  92423. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  92424. this._tmpMatrix = new BABYLON.Matrix();
  92425. this._tmpVector = new BABYLON.Vector3();
  92426. this._zeroVector = BABYLON.Vector3.Zero();
  92427. this._lookAtTmpMatrix = new BABYLON.Matrix();
  92428. /* Does nothing */
  92429. }
  92430. /**
  92431. * Initializes the behavior
  92432. */
  92433. AttachToBoxBehavior.prototype.init = function () {
  92434. /* Does nothing */
  92435. };
  92436. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  92437. var _this = this;
  92438. // Go over each face and calculate the angle between the face's normal and targetDirection
  92439. this._faceVectors.forEach(function (v) {
  92440. if (!_this._target.rotationQuaternion) {
  92441. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  92442. }
  92443. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  92444. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  92445. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  92446. });
  92447. // Return the face information of the one with the normal closeset to target direction
  92448. return this._faceVectors.reduce(function (min, p) {
  92449. if (min.ignore) {
  92450. return p;
  92451. }
  92452. else if (p.ignore) {
  92453. return min;
  92454. }
  92455. else {
  92456. return min.diff < p.diff ? min : p;
  92457. }
  92458. }, this._faceVectors[0]);
  92459. };
  92460. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  92461. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  92462. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  92463. this._lookAtTmpMatrix.invert();
  92464. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  92465. };
  92466. /**
  92467. * Attaches the AttachToBoxBehavior to the passed in mesh
  92468. * @param target The mesh that the specified node will be attached to
  92469. */
  92470. AttachToBoxBehavior.prototype.attach = function (target) {
  92471. var _this = this;
  92472. this._target = target;
  92473. this._scene = this._target.getScene();
  92474. // Every frame, update the app bars position
  92475. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92476. if (!_this._scene.activeCamera) {
  92477. return;
  92478. }
  92479. // Find the face closest to the cameras position
  92480. var cameraPos = _this._scene.activeCamera.position;
  92481. if (_this._scene.activeCamera.devicePosition) {
  92482. cameraPos = _this._scene.activeCamera.devicePosition;
  92483. }
  92484. var facing = _this._closestFace(cameraPos.subtract(target.position));
  92485. if (_this._scene.activeCamera.leftCamera) {
  92486. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92487. }
  92488. else {
  92489. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92490. }
  92491. // Get camera up direction
  92492. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  92493. // Ignore faces to not select a parrelel face for the up vector of the UI
  92494. _this._faceVectors.forEach(function (v) {
  92495. if (facing.direction.x && v.direction.x) {
  92496. v.ignore = true;
  92497. }
  92498. if (facing.direction.y && v.direction.y) {
  92499. v.ignore = true;
  92500. }
  92501. if (facing.direction.z && v.direction.z) {
  92502. v.ignore = true;
  92503. }
  92504. });
  92505. var facingUp = _this._closestFace(_this._tmpVector);
  92506. // Unignore faces
  92507. _this._faceVectors.forEach(function (v) {
  92508. v.ignore = false;
  92509. });
  92510. // Position the app bar on that face
  92511. _this.ui.position.copyFrom(target.position);
  92512. if (facing.direction.x) {
  92513. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92514. _this.ui.position.addInPlace(_this._tmpVector);
  92515. }
  92516. if (facing.direction.y) {
  92517. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92518. _this.ui.position.addInPlace(_this._tmpVector);
  92519. }
  92520. if (facing.direction.z) {
  92521. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92522. _this.ui.position.addInPlace(_this._tmpVector);
  92523. }
  92524. // Rotate to be oriented properly to the camera
  92525. if (!_this.ui.rotationQuaternion) {
  92526. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  92527. }
  92528. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  92529. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  92530. // Place ui the correct distance from the bottom of the mesh
  92531. if (facingUp.direction.x) {
  92532. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  92533. }
  92534. if (facingUp.direction.y) {
  92535. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  92536. }
  92537. if (facingUp.direction.z) {
  92538. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  92539. }
  92540. _this.ui.position.addInPlace(_this._tmpVector);
  92541. });
  92542. };
  92543. /**
  92544. * Detaches the behavior from the mesh
  92545. */
  92546. AttachToBoxBehavior.prototype.detach = function () {
  92547. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  92548. };
  92549. return AttachToBoxBehavior;
  92550. }());
  92551. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  92552. })(BABYLON || (BABYLON = {}));
  92553. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  92554. var BABYLON;
  92555. (function (BABYLON) {
  92556. /**
  92557. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  92558. */
  92559. var FadeInOutBehavior = /** @class */ (function () {
  92560. /**
  92561. * Instatiates the FadeInOutBehavior
  92562. */
  92563. function FadeInOutBehavior() {
  92564. var _this = this;
  92565. /**
  92566. * Time in milliseconds to delay before fading in (Default: 0)
  92567. */
  92568. this.delay = 0;
  92569. /**
  92570. * Time in milliseconds for the mesh to fade in (Default: 300)
  92571. */
  92572. this.fadeInTime = 300;
  92573. this._millisecondsPerFrame = 1000 / 60;
  92574. this._hovered = false;
  92575. this._hoverValue = 0;
  92576. this._ownerNode = null;
  92577. this._update = function () {
  92578. if (_this._ownerNode) {
  92579. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  92580. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  92581. if (_this._ownerNode.visibility > 1) {
  92582. _this._setAllVisibility(_this._ownerNode, 1);
  92583. _this._hoverValue = _this.fadeInTime + _this.delay;
  92584. return;
  92585. }
  92586. else if (_this._ownerNode.visibility < 0) {
  92587. _this._setAllVisibility(_this._ownerNode, 0);
  92588. if (_this._hoverValue < 0) {
  92589. _this._hoverValue = 0;
  92590. return;
  92591. }
  92592. }
  92593. setTimeout(_this._update, _this._millisecondsPerFrame);
  92594. }
  92595. };
  92596. }
  92597. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  92598. /**
  92599. * The name of the behavior
  92600. */
  92601. get: function () {
  92602. return "FadeInOut";
  92603. },
  92604. enumerable: true,
  92605. configurable: true
  92606. });
  92607. /**
  92608. * Initializes the behavior
  92609. */
  92610. FadeInOutBehavior.prototype.init = function () {
  92611. };
  92612. /**
  92613. * Attaches the fade behavior on the passed in mesh
  92614. * @param ownerNode The mesh that will be faded in/out once attached
  92615. */
  92616. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  92617. this._ownerNode = ownerNode;
  92618. this._setAllVisibility(this._ownerNode, 0);
  92619. };
  92620. /**
  92621. * Detaches the behavior from the mesh
  92622. */
  92623. FadeInOutBehavior.prototype.detach = function () {
  92624. this._ownerNode = null;
  92625. };
  92626. /**
  92627. * Triggers the mesh to begin fading in or out
  92628. * @param value if the object should fade in or out (true to fade in)
  92629. */
  92630. FadeInOutBehavior.prototype.fadeIn = function (value) {
  92631. this._hovered = value;
  92632. this._update();
  92633. };
  92634. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  92635. var _this = this;
  92636. mesh.visibility = value;
  92637. mesh.getChildMeshes().forEach(function (c) {
  92638. _this._setAllVisibility(c, value);
  92639. });
  92640. };
  92641. return FadeInOutBehavior;
  92642. }());
  92643. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  92644. })(BABYLON || (BABYLON = {}));
  92645. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  92646. var BABYLON;
  92647. (function (BABYLON) {
  92648. /**
  92649. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  92650. */
  92651. var Gizmo = /** @class */ (function () {
  92652. /**
  92653. * Creates a gizmo
  92654. * @param gizmoLayer The utility layer the gizmo will be added to
  92655. */
  92656. function Gizmo(
  92657. /** The utility layer the gizmo will be added to */
  92658. gizmoLayer) {
  92659. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92660. var _this = this;
  92661. this.gizmoLayer = gizmoLayer;
  92662. /**
  92663. * Ratio for the scale of the gizmo (Default: 1)
  92664. */
  92665. this.scaleRatio = 1;
  92666. this._tmpMatrix = new BABYLON.Matrix();
  92667. /**
  92668. * If a custom mesh has been set (Default: false)
  92669. */
  92670. this._customMeshSet = false;
  92671. /**
  92672. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  92673. */
  92674. this.updateGizmoRotationToMatchAttachedMesh = true;
  92675. /**
  92676. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  92677. */
  92678. this.updateGizmoPositionToMatchAttachedMesh = true;
  92679. /**
  92680. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  92681. */
  92682. this._updateScale = true;
  92683. this._interactionsEnabled = true;
  92684. this._tempVector = new BABYLON.Vector3();
  92685. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  92686. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  92687. _this._update();
  92688. });
  92689. this.attachedMesh = null;
  92690. }
  92691. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  92692. /**
  92693. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  92694. * * When set, interactions will be enabled
  92695. */
  92696. get: function () {
  92697. return this._attachedMesh;
  92698. },
  92699. set: function (value) {
  92700. this._attachedMesh = value;
  92701. this._rootMesh.setEnabled(value ? true : false);
  92702. this._attachedMeshChanged(value);
  92703. },
  92704. enumerable: true,
  92705. configurable: true
  92706. });
  92707. /**
  92708. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92709. * @param mesh The mesh to replace the default mesh of the gizmo
  92710. */
  92711. Gizmo.prototype.setCustomMesh = function (mesh) {
  92712. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92713. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92714. }
  92715. this._rootMesh.getChildMeshes().forEach(function (c) {
  92716. c.dispose();
  92717. });
  92718. mesh.parent = this._rootMesh;
  92719. this._customMeshSet = true;
  92720. };
  92721. Gizmo.prototype._attachedMeshChanged = function (value) {
  92722. };
  92723. /**
  92724. * @hidden
  92725. * Updates the gizmo to match the attached mesh's position/rotation
  92726. */
  92727. Gizmo.prototype._update = function () {
  92728. if (this.attachedMesh) {
  92729. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92730. if (!this._rootMesh.rotationQuaternion) {
  92731. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92732. }
  92733. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92734. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92735. if (this.attachedMesh.scaling.x < 0) {
  92736. this.attachedMesh.scaling.x *= -1;
  92737. }
  92738. if (this.attachedMesh.scaling.y < 0) {
  92739. this.attachedMesh.scaling.y *= -1;
  92740. }
  92741. if (this.attachedMesh.scaling.z < 0) {
  92742. this.attachedMesh.scaling.z *= -1;
  92743. }
  92744. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92745. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92746. this.attachedMesh.computeWorldMatrix();
  92747. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92748. }
  92749. else if (this._rootMesh.rotationQuaternion) {
  92750. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92751. }
  92752. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92753. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92754. }
  92755. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92756. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92757. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92758. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92759. }
  92760. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92761. var dist = this._tempVector.length() * this.scaleRatio;
  92762. this._rootMesh.scaling.set(dist, dist, dist);
  92763. }
  92764. }
  92765. };
  92766. /**
  92767. * Disposes of the gizmo
  92768. */
  92769. Gizmo.prototype.dispose = function () {
  92770. this._rootMesh.dispose();
  92771. if (this._beforeRenderObserver) {
  92772. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92773. }
  92774. };
  92775. return Gizmo;
  92776. }());
  92777. BABYLON.Gizmo = Gizmo;
  92778. })(BABYLON || (BABYLON = {}));
  92779. //# sourceMappingURL=babylon.gizmo.js.map
  92780. var BABYLON;
  92781. (function (BABYLON) {
  92782. /**
  92783. * Single axis drag gizmo
  92784. */
  92785. var AxisDragGizmo = /** @class */ (function (_super) {
  92786. __extends(AxisDragGizmo, _super);
  92787. /**
  92788. * Creates an AxisDragGizmo
  92789. * @param gizmoLayer The utility layer the gizmo will be added to
  92790. * @param dragAxis The axis which the gizmo will be able to drag on
  92791. * @param color The color of the gizmo
  92792. */
  92793. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  92794. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92795. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92796. var _this = _super.call(this, gizmoLayer) || this;
  92797. _this._pointerObserver = null;
  92798. /**
  92799. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92800. */
  92801. _this.snapDistance = 0;
  92802. /**
  92803. * Event that fires each time the gizmo snaps to a new location.
  92804. * * snapDistance is the the change in distance
  92805. */
  92806. _this.onSnapObservable = new BABYLON.Observable();
  92807. // Create Material
  92808. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92809. coloredMaterial.disableLighting = true;
  92810. coloredMaterial.emissiveColor = color;
  92811. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92812. hoverMaterial.disableLighting = true;
  92813. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92814. // Build mesh on root node
  92815. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92816. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  92817. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92818. arrowTail.color = coloredMaterial.emissiveColor;
  92819. arrow.addChild(arrowMesh);
  92820. arrow.addChild(arrowTail);
  92821. // Position arrow pointing in its drag axis
  92822. arrowMesh.scaling.scaleInPlace(0.05);
  92823. arrowMesh.material = coloredMaterial;
  92824. arrowMesh.rotation.x = Math.PI / 2;
  92825. arrowMesh.position.z += 0.3;
  92826. arrowTail.scaling.scaleInPlace(0.26);
  92827. arrowTail.rotation.x = Math.PI / 2;
  92828. arrowTail.material = coloredMaterial;
  92829. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92830. arrow.scaling.scaleInPlace(1 / 3);
  92831. _this._rootMesh.addChild(arrow);
  92832. var currentSnapDragDistance = 0;
  92833. var tmpVector = new BABYLON.Vector3();
  92834. var tmpSnapEvent = { snapDistance: 0 };
  92835. // Add drag behavior to handle events when the gizmo is dragged
  92836. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92837. _this.dragBehavior.moveAttached = false;
  92838. _this._rootMesh.addBehavior(_this.dragBehavior);
  92839. var localDelta = new BABYLON.Vector3();
  92840. var tmpMatrix = new BABYLON.Matrix();
  92841. _this.dragBehavior.onDragObservable.add(function (event) {
  92842. if (_this.attachedMesh) {
  92843. // Convert delta to local translation if it has a parent
  92844. if (_this.attachedMesh.parent) {
  92845. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92846. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  92847. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  92848. }
  92849. else {
  92850. localDelta.copyFrom(event.delta);
  92851. }
  92852. // Snapping logic
  92853. if (_this.snapDistance == 0) {
  92854. _this.attachedMesh.position.addInPlace(localDelta);
  92855. }
  92856. else {
  92857. currentSnapDragDistance += event.dragDistance;
  92858. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92859. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  92860. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92861. localDelta.normalizeToRef(tmpVector);
  92862. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  92863. _this.attachedMesh.position.addInPlace(tmpVector);
  92864. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92865. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92866. }
  92867. }
  92868. }
  92869. });
  92870. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92871. if (_this._customMeshSet) {
  92872. return;
  92873. }
  92874. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92875. var material = isHovered ? hoverMaterial : coloredMaterial;
  92876. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92877. m.material = material;
  92878. if (m.color) {
  92879. m.color = material.emissiveColor;
  92880. }
  92881. });
  92882. });
  92883. return _this;
  92884. }
  92885. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  92886. if (this.dragBehavior) {
  92887. this.dragBehavior.enabled = value ? true : false;
  92888. }
  92889. };
  92890. /**
  92891. * Disposes of the gizmo
  92892. */
  92893. AxisDragGizmo.prototype.dispose = function () {
  92894. this.onSnapObservable.clear();
  92895. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92896. this.dragBehavior.detach();
  92897. _super.prototype.dispose.call(this);
  92898. };
  92899. return AxisDragGizmo;
  92900. }(BABYLON.Gizmo));
  92901. BABYLON.AxisDragGizmo = AxisDragGizmo;
  92902. })(BABYLON || (BABYLON = {}));
  92903. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  92904. var BABYLON;
  92905. (function (BABYLON) {
  92906. /**
  92907. * Single axis scale gizmo
  92908. */
  92909. var AxisScaleGizmo = /** @class */ (function (_super) {
  92910. __extends(AxisScaleGizmo, _super);
  92911. /**
  92912. * Creates an AxisScaleGizmo
  92913. * @param gizmoLayer The utility layer the gizmo will be added to
  92914. * @param dragAxis The axis which the gizmo will be able to scale on
  92915. * @param color The color of the gizmo
  92916. */
  92917. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  92918. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92919. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92920. var _this = _super.call(this, gizmoLayer) || this;
  92921. _this._pointerObserver = null;
  92922. /**
  92923. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92924. */
  92925. _this.snapDistance = 0;
  92926. /**
  92927. * Event that fires each time the gizmo snaps to a new location.
  92928. * * snapDistance is the the change in distance
  92929. */
  92930. _this.onSnapObservable = new BABYLON.Observable();
  92931. /**
  92932. * If the scaling operation should be done on all axis (default: false)
  92933. */
  92934. _this.uniformScaling = false;
  92935. // Create Material
  92936. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92937. _this._coloredMaterial.disableLighting = true;
  92938. _this._coloredMaterial.emissiveColor = color;
  92939. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92940. hoverMaterial.disableLighting = true;
  92941. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92942. // Build mesh on root node
  92943. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92944. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  92945. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92946. arrowTail.color = _this._coloredMaterial.emissiveColor;
  92947. arrow.addChild(arrowMesh);
  92948. arrow.addChild(arrowTail);
  92949. // Position arrow pointing in its drag axis
  92950. arrowMesh.scaling.scaleInPlace(0.1);
  92951. arrowMesh.material = _this._coloredMaterial;
  92952. arrowMesh.rotation.x = Math.PI / 2;
  92953. arrowMesh.position.z += 0.3;
  92954. arrowTail.scaling.scaleInPlace(0.26);
  92955. arrowTail.rotation.x = Math.PI / 2;
  92956. arrowTail.material = _this._coloredMaterial;
  92957. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92958. _this._rootMesh.addChild(arrow);
  92959. arrow.scaling.scaleInPlace(1 / 3);
  92960. // Add drag behavior to handle events when the gizmo is dragged
  92961. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92962. _this.dragBehavior.moveAttached = false;
  92963. _this._rootMesh.addBehavior(_this.dragBehavior);
  92964. var currentSnapDragDistance = 0;
  92965. var tmpVector = new BABYLON.Vector3();
  92966. var tmpSnapEvent = { snapDistance: 0 };
  92967. _this.dragBehavior.onDragObservable.add(function (event) {
  92968. if (_this.attachedMesh) {
  92969. // Snapping logic
  92970. var snapped = false;
  92971. var dragSteps = 0;
  92972. if (_this.uniformScaling) {
  92973. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  92974. if (tmpVector.y < 0) {
  92975. tmpVector.scaleInPlace(-1);
  92976. }
  92977. }
  92978. else {
  92979. tmpVector.copyFrom(dragAxis);
  92980. }
  92981. if (_this.snapDistance == 0) {
  92982. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92983. }
  92984. else {
  92985. currentSnapDragDistance += event.dragDistance;
  92986. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92987. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92988. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92989. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92990. snapped = true;
  92991. }
  92992. else {
  92993. tmpVector.scaleInPlace(0);
  92994. }
  92995. }
  92996. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92997. if (snapped) {
  92998. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92999. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93000. }
  93001. }
  93002. });
  93003. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93004. if (_this._customMeshSet) {
  93005. return;
  93006. }
  93007. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93008. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  93009. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93010. m.material = material;
  93011. if (m.color) {
  93012. m.color = material.emissiveColor;
  93013. }
  93014. });
  93015. });
  93016. return _this;
  93017. }
  93018. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  93019. if (this.dragBehavior) {
  93020. this.dragBehavior.enabled = value ? true : false;
  93021. }
  93022. };
  93023. /**
  93024. * Disposes of the gizmo
  93025. */
  93026. AxisScaleGizmo.prototype.dispose = function () {
  93027. this.onSnapObservable.clear();
  93028. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93029. this.dragBehavior.detach();
  93030. _super.prototype.dispose.call(this);
  93031. };
  93032. /**
  93033. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93034. * @param mesh The mesh to replace the default mesh of the gizmo
  93035. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  93036. */
  93037. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  93038. var _this = this;
  93039. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  93040. _super.prototype.setCustomMesh.call(this, mesh);
  93041. if (useGizmoMaterial) {
  93042. this._rootMesh.getChildMeshes().forEach(function (m) {
  93043. m.material = _this._coloredMaterial;
  93044. if (m.color) {
  93045. m.color = _this._coloredMaterial.emissiveColor;
  93046. }
  93047. });
  93048. this._customMeshSet = false;
  93049. }
  93050. };
  93051. return AxisScaleGizmo;
  93052. }(BABYLON.Gizmo));
  93053. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  93054. })(BABYLON || (BABYLON = {}));
  93055. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  93056. var BABYLON;
  93057. (function (BABYLON) {
  93058. /**
  93059. * Single plane rotation gizmo
  93060. */
  93061. var PlaneRotationGizmo = /** @class */ (function (_super) {
  93062. __extends(PlaneRotationGizmo, _super);
  93063. /**
  93064. * Creates a PlaneRotationGizmo
  93065. * @param gizmoLayer The utility layer the gizmo will be added to
  93066. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  93067. * @param color The color of the gizmo
  93068. */
  93069. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  93070. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93071. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93072. var _this = _super.call(this, gizmoLayer) || this;
  93073. _this._pointerObserver = null;
  93074. /**
  93075. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  93076. */
  93077. _this.snapDistance = 0;
  93078. /**
  93079. * Event that fires each time the gizmo snaps to a new location.
  93080. * * snapDistance is the the change in distance
  93081. */
  93082. _this.onSnapObservable = new BABYLON.Observable();
  93083. // Create Material
  93084. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93085. coloredMaterial.disableLighting = true;
  93086. coloredMaterial.emissiveColor = color;
  93087. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93088. hoverMaterial.disableLighting = true;
  93089. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93090. // Build mesh on root node
  93091. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93092. // Create circle out of lines
  93093. var tessellation = 20;
  93094. var radius = 0.8;
  93095. var points = new Array();
  93096. for (var i = 0; i < tessellation; i++) {
  93097. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  93098. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  93099. }
  93100. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  93101. rotationMesh.color = coloredMaterial.emissiveColor;
  93102. // Position arrow pointing in its drag axis
  93103. rotationMesh.scaling.scaleInPlace(0.26);
  93104. rotationMesh.material = coloredMaterial;
  93105. rotationMesh.rotation.x = Math.PI / 2;
  93106. parentMesh.addChild(rotationMesh);
  93107. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  93108. _this._rootMesh.addChild(parentMesh);
  93109. parentMesh.scaling.scaleInPlace(1 / 3);
  93110. // Add drag behavior to handle events when the gizmo is dragged
  93111. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  93112. _this.dragBehavior.moveAttached = false;
  93113. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  93114. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  93115. _this._rootMesh.addBehavior(_this.dragBehavior);
  93116. var lastDragPosition = new BABYLON.Vector3();
  93117. _this.dragBehavior.onDragStartObservable.add(function (e) {
  93118. if (_this.attachedMesh) {
  93119. lastDragPosition.copyFrom(e.dragPlanePoint);
  93120. }
  93121. });
  93122. var rotationMatrix = new BABYLON.Matrix();
  93123. var planeNormalTowardsCamera = new BABYLON.Vector3();
  93124. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  93125. var tmpSnapEvent = { snapDistance: 0 };
  93126. var currentSnapDragDistance = 0;
  93127. var tmpMatrix = new BABYLON.Matrix();
  93128. var tmpVector = new BABYLON.Vector3();
  93129. var amountToRotate = new BABYLON.Quaternion();
  93130. _this.dragBehavior.onDragObservable.add(function (event) {
  93131. if (_this.attachedMesh) {
  93132. if (!_this.attachedMesh.rotationQuaternion) {
  93133. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93134. }
  93135. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  93136. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  93137. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  93138. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  93139. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  93140. var angle = Math.atan2(cross.length(), dot);
  93141. planeNormalTowardsCamera.copyFrom(planeNormal);
  93142. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  93143. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93144. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  93145. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  93146. }
  93147. // Flip up vector depending on which side the camera is on
  93148. if (gizmoLayer.utilityLayerScene.activeCamera) {
  93149. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  93150. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  93151. planeNormalTowardsCamera.scaleInPlace(-1);
  93152. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  93153. }
  93154. }
  93155. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  93156. if (halfCircleSide)
  93157. angle = -angle;
  93158. // Snapping logic
  93159. var snapped = false;
  93160. if (_this.snapDistance != 0) {
  93161. currentSnapDragDistance += angle;
  93162. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93163. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93164. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93165. angle = _this.snapDistance * dragSteps;
  93166. snapped = true;
  93167. }
  93168. else {
  93169. angle = 0;
  93170. }
  93171. }
  93172. // If the mesh has a parent, convert needed world rotation to local rotation
  93173. tmpMatrix.reset();
  93174. if (_this.attachedMesh.parent) {
  93175. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93176. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  93177. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  93178. }
  93179. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  93180. var quaternionCoefficient = Math.sin(angle / 2);
  93181. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  93182. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  93183. if (tmpMatrix.determinant() > 0) {
  93184. amountToRotate.toEulerAnglesToRef(tmpVector);
  93185. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  93186. }
  93187. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93188. // Rotate selected mesh quaternion over fixed axis
  93189. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  93190. }
  93191. else {
  93192. // Rotate selected mesh quaternion over rotated axis
  93193. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  93194. }
  93195. lastDragPosition.copyFrom(event.dragPlanePoint);
  93196. if (snapped) {
  93197. tmpSnapEvent.snapDistance = angle;
  93198. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93199. }
  93200. }
  93201. });
  93202. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93203. if (_this._customMeshSet) {
  93204. return;
  93205. }
  93206. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93207. var material = isHovered ? hoverMaterial : coloredMaterial;
  93208. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93209. m.material = material;
  93210. if (m.color) {
  93211. m.color = material.emissiveColor;
  93212. }
  93213. });
  93214. });
  93215. return _this;
  93216. }
  93217. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  93218. if (this.dragBehavior) {
  93219. this.dragBehavior.enabled = value ? true : false;
  93220. }
  93221. };
  93222. /**
  93223. * Disposes of the gizmo
  93224. */
  93225. PlaneRotationGizmo.prototype.dispose = function () {
  93226. this.onSnapObservable.clear();
  93227. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93228. this.dragBehavior.detach();
  93229. _super.prototype.dispose.call(this);
  93230. };
  93231. return PlaneRotationGizmo;
  93232. }(BABYLON.Gizmo));
  93233. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  93234. })(BABYLON || (BABYLON = {}));
  93235. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  93236. var BABYLON;
  93237. (function (BABYLON) {
  93238. /**
  93239. * Gizmo that enables dragging a mesh along 3 axis
  93240. */
  93241. var PositionGizmo = /** @class */ (function (_super) {
  93242. __extends(PositionGizmo, _super);
  93243. /**
  93244. * Creates a PositionGizmo
  93245. * @param gizmoLayer The utility layer the gizmo will be added to
  93246. */
  93247. function PositionGizmo(gizmoLayer) {
  93248. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93249. var _this = _super.call(this, gizmoLayer) || this;
  93250. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93251. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93252. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93253. _this.attachedMesh = null;
  93254. return _this;
  93255. }
  93256. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  93257. set: function (mesh) {
  93258. if (this.xGizmo) {
  93259. this.xGizmo.attachedMesh = mesh;
  93260. this.yGizmo.attachedMesh = mesh;
  93261. this.zGizmo.attachedMesh = mesh;
  93262. }
  93263. },
  93264. enumerable: true,
  93265. configurable: true
  93266. });
  93267. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93268. get: function () {
  93269. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93270. },
  93271. set: function (value) {
  93272. if (this.xGizmo) {
  93273. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93274. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93275. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93276. }
  93277. },
  93278. enumerable: true,
  93279. configurable: true
  93280. });
  93281. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  93282. get: function () {
  93283. return this.xGizmo.snapDistance;
  93284. },
  93285. /**
  93286. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93287. */
  93288. set: function (value) {
  93289. if (this.xGizmo) {
  93290. this.xGizmo.snapDistance = value;
  93291. this.yGizmo.snapDistance = value;
  93292. this.zGizmo.snapDistance = value;
  93293. }
  93294. },
  93295. enumerable: true,
  93296. configurable: true
  93297. });
  93298. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  93299. get: function () {
  93300. return this.xGizmo.scaleRatio;
  93301. },
  93302. /**
  93303. * Ratio for the scale of the gizmo (Default: 1)
  93304. */
  93305. set: function (value) {
  93306. if (this.xGizmo) {
  93307. this.xGizmo.scaleRatio = value;
  93308. this.yGizmo.scaleRatio = value;
  93309. this.zGizmo.scaleRatio = value;
  93310. }
  93311. },
  93312. enumerable: true,
  93313. configurable: true
  93314. });
  93315. /**
  93316. * Disposes of the gizmo
  93317. */
  93318. PositionGizmo.prototype.dispose = function () {
  93319. this.xGizmo.dispose();
  93320. this.yGizmo.dispose();
  93321. this.zGizmo.dispose();
  93322. };
  93323. /**
  93324. * CustomMeshes are not supported by this gizmo
  93325. * @param mesh The mesh to replace the default mesh of the gizmo
  93326. */
  93327. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  93328. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  93329. };
  93330. return PositionGizmo;
  93331. }(BABYLON.Gizmo));
  93332. BABYLON.PositionGizmo = PositionGizmo;
  93333. })(BABYLON || (BABYLON = {}));
  93334. //# sourceMappingURL=babylon.positionGizmo.js.map
  93335. var BABYLON;
  93336. (function (BABYLON) {
  93337. /**
  93338. * Gizmo that enables rotating a mesh along 3 axis
  93339. */
  93340. var RotationGizmo = /** @class */ (function (_super) {
  93341. __extends(RotationGizmo, _super);
  93342. /**
  93343. * Creates a RotationGizmo
  93344. * @param gizmoLayer The utility layer the gizmo will be added to
  93345. */
  93346. function RotationGizmo(gizmoLayer) {
  93347. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93348. var _this = _super.call(this, gizmoLayer) || this;
  93349. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93350. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93351. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93352. _this.attachedMesh = null;
  93353. return _this;
  93354. }
  93355. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  93356. set: function (mesh) {
  93357. if (this.xGizmo) {
  93358. this.xGizmo.attachedMesh = mesh;
  93359. this.yGizmo.attachedMesh = mesh;
  93360. this.zGizmo.attachedMesh = mesh;
  93361. }
  93362. },
  93363. enumerable: true,
  93364. configurable: true
  93365. });
  93366. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93367. get: function () {
  93368. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93369. },
  93370. set: function (value) {
  93371. if (this.xGizmo) {
  93372. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93373. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93374. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93375. }
  93376. },
  93377. enumerable: true,
  93378. configurable: true
  93379. });
  93380. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  93381. get: function () {
  93382. return this.xGizmo.snapDistance;
  93383. },
  93384. /**
  93385. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93386. */
  93387. set: function (value) {
  93388. if (this.xGizmo) {
  93389. this.xGizmo.snapDistance = value;
  93390. this.yGizmo.snapDistance = value;
  93391. this.zGizmo.snapDistance = value;
  93392. }
  93393. },
  93394. enumerable: true,
  93395. configurable: true
  93396. });
  93397. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  93398. get: function () {
  93399. return this.xGizmo.scaleRatio;
  93400. },
  93401. /**
  93402. * Ratio for the scale of the gizmo (Default: 1)
  93403. */
  93404. set: function (value) {
  93405. if (this.xGizmo) {
  93406. this.xGizmo.scaleRatio = value;
  93407. this.yGizmo.scaleRatio = value;
  93408. this.zGizmo.scaleRatio = value;
  93409. }
  93410. },
  93411. enumerable: true,
  93412. configurable: true
  93413. });
  93414. /**
  93415. * Disposes of the gizmo
  93416. */
  93417. RotationGizmo.prototype.dispose = function () {
  93418. this.xGizmo.dispose();
  93419. this.yGizmo.dispose();
  93420. this.zGizmo.dispose();
  93421. };
  93422. /**
  93423. * CustomMeshes are not supported by this gizmo
  93424. * @param mesh The mesh to replace the default mesh of the gizmo
  93425. */
  93426. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  93427. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  93428. };
  93429. return RotationGizmo;
  93430. }(BABYLON.Gizmo));
  93431. BABYLON.RotationGizmo = RotationGizmo;
  93432. })(BABYLON || (BABYLON = {}));
  93433. //# sourceMappingURL=babylon.rotationGizmo.js.map
  93434. var BABYLON;
  93435. (function (BABYLON) {
  93436. /**
  93437. * Gizmo that enables scaling a mesh along 3 axis
  93438. */
  93439. var ScaleGizmo = /** @class */ (function (_super) {
  93440. __extends(ScaleGizmo, _super);
  93441. /**
  93442. * Creates a ScaleGizmo
  93443. * @param gizmoLayer The utility layer the gizmo will be added to
  93444. */
  93445. function ScaleGizmo(gizmoLayer) {
  93446. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93447. var _this = _super.call(this, gizmoLayer) || this;
  93448. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93449. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93450. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93451. // Create uniform scale gizmo
  93452. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  93453. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93454. _this._uniformGizmo.uniformScaling = true;
  93455. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  93456. octahedron.scaling.scaleInPlace(0.007);
  93457. _this._uniformGizmo.setCustomMesh(octahedron, true);
  93458. _this.attachedMesh = null;
  93459. return _this;
  93460. }
  93461. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  93462. set: function (mesh) {
  93463. if (this.xGizmo) {
  93464. this.xGizmo.attachedMesh = mesh;
  93465. this.yGizmo.attachedMesh = mesh;
  93466. this.zGizmo.attachedMesh = mesh;
  93467. this._uniformGizmo.attachedMesh = mesh;
  93468. }
  93469. },
  93470. enumerable: true,
  93471. configurable: true
  93472. });
  93473. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93474. get: function () {
  93475. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93476. },
  93477. set: function (value) {
  93478. if (this.xGizmo) {
  93479. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93480. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93481. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93482. }
  93483. },
  93484. enumerable: true,
  93485. configurable: true
  93486. });
  93487. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  93488. get: function () {
  93489. return this.xGizmo.snapDistance;
  93490. },
  93491. /**
  93492. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93493. */
  93494. set: function (value) {
  93495. if (this.xGizmo) {
  93496. this.xGizmo.snapDistance = value;
  93497. this.yGizmo.snapDistance = value;
  93498. this.zGizmo.snapDistance = value;
  93499. this._uniformGizmo.snapDistance = value;
  93500. }
  93501. },
  93502. enumerable: true,
  93503. configurable: true
  93504. });
  93505. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  93506. get: function () {
  93507. return this.xGizmo.scaleRatio;
  93508. },
  93509. /**
  93510. * Ratio for the scale of the gizmo (Default: 1)
  93511. */
  93512. set: function (value) {
  93513. if (this.xGizmo) {
  93514. this.xGizmo.scaleRatio = value;
  93515. this.yGizmo.scaleRatio = value;
  93516. this.zGizmo.scaleRatio = value;
  93517. this._uniformGizmo.scaleRatio = value;
  93518. }
  93519. },
  93520. enumerable: true,
  93521. configurable: true
  93522. });
  93523. /**
  93524. * Disposes of the gizmo
  93525. */
  93526. ScaleGizmo.prototype.dispose = function () {
  93527. this.xGizmo.dispose();
  93528. this.yGizmo.dispose();
  93529. this.zGizmo.dispose();
  93530. this._uniformGizmo.dispose();
  93531. };
  93532. return ScaleGizmo;
  93533. }(BABYLON.Gizmo));
  93534. BABYLON.ScaleGizmo = ScaleGizmo;
  93535. })(BABYLON || (BABYLON = {}));
  93536. //# sourceMappingURL=babylon.scaleGizmo.js.map
  93537. var BABYLON;
  93538. (function (BABYLON) {
  93539. /**
  93540. * Bounding box gizmo
  93541. */
  93542. var BoundingBoxGizmo = /** @class */ (function (_super) {
  93543. __extends(BoundingBoxGizmo, _super);
  93544. /**
  93545. * Creates an BoundingBoxGizmo
  93546. * @param gizmoLayer The utility layer the gizmo will be added to
  93547. * @param color The color of the gizmo
  93548. */
  93549. function BoundingBoxGizmo(color, gizmoLayer) {
  93550. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93551. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  93552. var _this = _super.call(this, gizmoLayer) || this;
  93553. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  93554. _this._renderObserver = null;
  93555. _this._pointerObserver = null;
  93556. _this._scaleDragSpeed = 0.2;
  93557. _this._tmpQuaternion = new BABYLON.Quaternion();
  93558. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93559. _this._tmpRotationMatrix = new BABYLON.Matrix();
  93560. /**
  93561. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  93562. */
  93563. _this.ignoreChildren = false;
  93564. /**
  93565. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  93566. */
  93567. _this.includeChildPredicate = null;
  93568. /**
  93569. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  93570. */
  93571. _this.rotationSphereSize = 0.1;
  93572. /**
  93573. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  93574. */
  93575. _this.scaleBoxSize = 0.1;
  93576. /**
  93577. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  93578. */
  93579. _this.fixedDragMeshScreenSize = false;
  93580. /**
  93581. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  93582. */
  93583. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  93584. /**
  93585. * Fired when a rotation sphere or scale box is dragged
  93586. */
  93587. _this.onDragStartObservable = new BABYLON.Observable();
  93588. /**
  93589. * Fired when a scale box is dragged
  93590. */
  93591. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  93592. /**
  93593. * Fired when a scale box drag is ended
  93594. */
  93595. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  93596. /**
  93597. * Fired when a rotation sphere is dragged
  93598. */
  93599. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  93600. /**
  93601. * Fired when a rotation sphere drag is ended
  93602. */
  93603. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  93604. /**
  93605. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  93606. */
  93607. _this.scalePivot = null;
  93608. _this._existingMeshScale = new BABYLON.Vector3();
  93609. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  93610. _this._updateScale = false;
  93611. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  93612. // Create Materials
  93613. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93614. coloredMaterial.disableLighting = true;
  93615. coloredMaterial.emissiveColor = color;
  93616. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93617. hoverColoredMaterial.disableLighting = true;
  93618. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93619. // Build bounding box out of lines
  93620. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93621. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  93622. var lines = [];
  93623. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  93624. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93625. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93626. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93627. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93628. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93629. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93630. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93631. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93632. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93633. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93634. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93635. lines.forEach(function (l) {
  93636. l.color = color;
  93637. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  93638. l.isPickable = false;
  93639. _this._lineBoundingBox.addChild(l);
  93640. });
  93641. _this._rootMesh.addChild(_this._lineBoundingBox);
  93642. // Create rotation spheres
  93643. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93644. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  93645. var _loop_1 = function (i_1) {
  93646. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  93647. sphere.rotationQuaternion = new BABYLON.Quaternion();
  93648. sphere.material = coloredMaterial;
  93649. // Drag behavior
  93650. _dragBehavior = new BABYLON.PointerDragBehavior({});
  93651. _dragBehavior.moveAttached = false;
  93652. _dragBehavior.updateDragPlane = false;
  93653. sphere.addBehavior(_dragBehavior);
  93654. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  93655. var totalTurnAmountOfDrag = 0;
  93656. _dragBehavior.onDragStartObservable.add(function (event) {
  93657. startingTurnDirection.copyFrom(sphere.forward);
  93658. totalTurnAmountOfDrag = 0;
  93659. });
  93660. _dragBehavior.onDragObservable.add(function (event) {
  93661. _this.onRotationSphereDragObservable.notifyObservers({});
  93662. if (_this.attachedMesh) {
  93663. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  93664. var worldDragDirection = startingTurnDirection;
  93665. // Project the world right on to the drag plane
  93666. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  93667. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  93668. // project drag delta on to the resulting drag axis and rotate based on that
  93669. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  93670. // Make rotation relative to size of mesh.
  93671. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93672. // Rotate based on axis
  93673. if (!_this.attachedMesh.rotationQuaternion) {
  93674. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93675. }
  93676. if (!_this._anchorMesh.rotationQuaternion) {
  93677. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  93678. }
  93679. // Do not allow the object to turn more than a full circle
  93680. totalTurnAmountOfDrag += projectDist;
  93681. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  93682. if (i_1 >= 8) {
  93683. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  93684. }
  93685. else if (i_1 >= 4) {
  93686. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  93687. }
  93688. else {
  93689. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  93690. }
  93691. // Rotate around center of bounding box
  93692. _this._anchorMesh.addChild(_this.attachedMesh);
  93693. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  93694. _this._anchorMesh.removeChild(_this.attachedMesh);
  93695. }
  93696. _this.updateBoundingBox();
  93697. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  93698. }
  93699. });
  93700. // Selection/deselection
  93701. _dragBehavior.onDragStartObservable.add(function () {
  93702. _this.onDragStartObservable.notifyObservers({});
  93703. _this._selectNode(sphere);
  93704. });
  93705. _dragBehavior.onDragEndObservable.add(function () {
  93706. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93707. _this._selectNode(null);
  93708. });
  93709. this_1._rotateSpheresParent.addChild(sphere);
  93710. };
  93711. var this_1 = this, _dragBehavior;
  93712. for (var i_1 = 0; i_1 < 12; i_1++) {
  93713. _loop_1(i_1);
  93714. }
  93715. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93716. // Create scale cubes
  93717. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93718. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93719. for (var i = 0; i < 2; i++) {
  93720. for (var j = 0; j < 2; j++) {
  93721. var _loop_2 = function () {
  93722. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93723. box.material = coloredMaterial;
  93724. // Dragging logic
  93725. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93726. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93727. _dragBehavior.moveAttached = false;
  93728. box.addBehavior(_dragBehavior);
  93729. _dragBehavior.onDragObservable.add(function (event) {
  93730. _this.onScaleBoxDragObservable.notifyObservers({});
  93731. if (_this.attachedMesh) {
  93732. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  93733. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93734. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93735. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93736. _this.updateBoundingBox();
  93737. if (_this.scalePivot) {
  93738. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93739. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93740. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93741. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93742. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93743. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93744. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93745. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93746. }
  93747. else {
  93748. // Scale from the position of the opposite corner
  93749. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93750. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93751. }
  93752. _this._anchorMesh.addChild(_this.attachedMesh);
  93753. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93754. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93755. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93756. }
  93757. _this._anchorMesh.removeChild(_this.attachedMesh);
  93758. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  93759. }
  93760. });
  93761. // Selection/deselection
  93762. _dragBehavior.onDragStartObservable.add(function () {
  93763. _this.onDragStartObservable.notifyObservers({});
  93764. _this._selectNode(box);
  93765. });
  93766. _dragBehavior.onDragEndObservable.add(function () {
  93767. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93768. _this._selectNode(null);
  93769. });
  93770. this_2._scaleBoxesParent.addChild(box);
  93771. };
  93772. var this_2 = this, _dragBehavior;
  93773. for (var k = 0; k < 2; k++) {
  93774. _loop_2();
  93775. }
  93776. }
  93777. }
  93778. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93779. // Hover color change
  93780. var pointerIds = new Array();
  93781. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93782. if (!pointerIds[pointerInfo.event.pointerId]) {
  93783. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  93784. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  93785. pointerIds[pointerInfo.event.pointerId] = mesh;
  93786. mesh.material = hoverColoredMaterial;
  93787. }
  93788. });
  93789. }
  93790. else {
  93791. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  93792. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  93793. delete pointerIds[pointerInfo.event.pointerId];
  93794. }
  93795. }
  93796. });
  93797. // Update bounding box positions
  93798. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  93799. // Only update the bouding box if scaling has changed
  93800. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  93801. _this.updateBoundingBox();
  93802. }
  93803. });
  93804. _this.updateBoundingBox();
  93805. return _this;
  93806. }
  93807. /** @hidden */
  93808. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  93809. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  93810. // Save old pivot and set pivot to 0,0,0
  93811. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  93812. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  93813. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  93814. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  93815. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  93816. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  93817. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  93818. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  93819. }
  93820. }
  93821. BoundingBoxGizmo._PivotCached++;
  93822. };
  93823. /** @hidden */
  93824. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  93825. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  93826. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  93827. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  93828. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  93829. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  93830. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  93831. }
  93832. this._PivotCached--;
  93833. };
  93834. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  93835. if (value) {
  93836. // Reset anchor mesh to match attached mesh's scale
  93837. // This is needed to avoid invalid box/sphere position on first drag
  93838. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  93839. this._anchorMesh.addChild(value);
  93840. this._anchorMesh.removeChild(value);
  93841. BoundingBoxGizmo._RestorePivotPoint(value);
  93842. this.updateBoundingBox();
  93843. }
  93844. };
  93845. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  93846. this._rotateSpheresParent.getChildMeshes()
  93847. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  93848. m.isVisible = (!selectedMesh || m == selectedMesh);
  93849. });
  93850. };
  93851. /**
  93852. * Updates the bounding box information for the Gizmo
  93853. */
  93854. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  93855. if (this.attachedMesh) {
  93856. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  93857. this._update();
  93858. // Rotate based on axis
  93859. if (!this.attachedMesh.rotationQuaternion) {
  93860. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  93861. }
  93862. if (!this._anchorMesh.rotationQuaternion) {
  93863. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  93864. }
  93865. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93866. // Store original position and reset mesh to origin before computing the bounding box
  93867. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93868. this._tmpVector.copyFrom(this.attachedMesh.position);
  93869. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  93870. this.attachedMesh.position.set(0, 0, 0);
  93871. // Update bounding dimensions/positions
  93872. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  93873. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  93874. // Update gizmo to match bounding box scaling and rotation
  93875. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  93876. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93877. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  93878. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  93879. this._lineBoundingBox.computeWorldMatrix();
  93880. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  93881. // restore position/rotation values
  93882. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  93883. this.attachedMesh.position.copyFrom(this._tmpVector);
  93884. }
  93885. // Update rotation sphere locations
  93886. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  93887. for (var i = 0; i < 3; i++) {
  93888. for (var j = 0; j < 2; j++) {
  93889. for (var k = 0; k < 2; k++) {
  93890. var index = ((i * 4) + (j * 2)) + k;
  93891. if (i == 0) {
  93892. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93893. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93894. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93895. }
  93896. if (i == 1) {
  93897. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  93898. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93899. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93900. }
  93901. if (i == 2) {
  93902. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  93903. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93904. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93905. }
  93906. if (this.fixedDragMeshScreenSize) {
  93907. this._rootMesh.computeWorldMatrix();
  93908. this._rotateSpheresParent.computeWorldMatrix();
  93909. rotateSpheres[index].computeWorldMatrix();
  93910. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93911. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93912. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93913. }
  93914. else {
  93915. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  93916. }
  93917. }
  93918. }
  93919. }
  93920. // Update scale box locations
  93921. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  93922. for (var i = 0; i < 2; i++) {
  93923. for (var j = 0; j < 2; j++) {
  93924. for (var k = 0; k < 2; k++) {
  93925. var index = ((i * 4) + (j * 2)) + k;
  93926. if (scaleBoxes[index]) {
  93927. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93928. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93929. if (this.fixedDragMeshScreenSize) {
  93930. this._rootMesh.computeWorldMatrix();
  93931. this._scaleBoxesParent.computeWorldMatrix();
  93932. scaleBoxes[index].computeWorldMatrix();
  93933. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93934. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93935. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93936. }
  93937. else {
  93938. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  93939. }
  93940. }
  93941. }
  93942. }
  93943. }
  93944. if (this.attachedMesh) {
  93945. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  93946. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  93947. }
  93948. };
  93949. /**
  93950. * Enables rotation on the specified axis and disables rotation on the others
  93951. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  93952. */
  93953. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  93954. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  93955. if (i < 4) {
  93956. m.setEnabled(axis.indexOf("x") != -1);
  93957. }
  93958. else if (i < 8) {
  93959. m.setEnabled(axis.indexOf("y") != -1);
  93960. }
  93961. else {
  93962. m.setEnabled(axis.indexOf("z") != -1);
  93963. }
  93964. });
  93965. };
  93966. /**
  93967. * Disposes of the gizmo
  93968. */
  93969. BoundingBoxGizmo.prototype.dispose = function () {
  93970. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93971. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  93972. this._lineBoundingBox.dispose();
  93973. this._rotateSpheresParent.dispose();
  93974. this._scaleBoxesParent.dispose();
  93975. _super.prototype.dispose.call(this);
  93976. };
  93977. /**
  93978. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  93979. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  93980. * @returns the bounding box mesh with the passed in mesh as a child
  93981. */
  93982. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  93983. var makeNotPickable = function (root) {
  93984. root.isPickable = false;
  93985. root.getChildMeshes().forEach(function (c) {
  93986. makeNotPickable(c);
  93987. });
  93988. };
  93989. makeNotPickable(mesh);
  93990. // Reset position to get boudning box from origin with no rotation
  93991. if (!mesh.rotationQuaternion) {
  93992. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  93993. }
  93994. var oldPos = mesh.position.clone();
  93995. var oldRot = mesh.rotationQuaternion.clone();
  93996. mesh.rotationQuaternion.set(0, 0, 0, 1);
  93997. mesh.position.set(0, 0, 0);
  93998. // Update bounding dimensions/positions
  93999. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  94000. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  94001. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  94002. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94003. // Restore original positions
  94004. mesh.addChild(box);
  94005. mesh.rotationQuaternion.copyFrom(oldRot);
  94006. mesh.position.copyFrom(oldPos);
  94007. // Reverse parenting
  94008. mesh.removeChild(box);
  94009. box.addChild(mesh);
  94010. box.visibility = 0;
  94011. return box;
  94012. };
  94013. /**
  94014. * CustomMeshes are not supported by this gizmo
  94015. * @param mesh The mesh to replace the default mesh of the gizmo
  94016. */
  94017. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  94018. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  94019. };
  94020. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  94021. // store/remove pivot point should only be applied during their outermost calls
  94022. BoundingBoxGizmo._PivotCached = 0;
  94023. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  94024. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  94025. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  94026. return BoundingBoxGizmo;
  94027. }(BABYLON.Gizmo));
  94028. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  94029. })(BABYLON || (BABYLON = {}));
  94030. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  94031. var BABYLON;
  94032. (function (BABYLON) {
  94033. /**
  94034. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  94035. */
  94036. var GizmoManager = /** @class */ (function () {
  94037. /**
  94038. * Instatiates a gizmo manager
  94039. * @param scene the scene to overlay the gizmos on top of
  94040. */
  94041. function GizmoManager(scene) {
  94042. var _this = this;
  94043. this.scene = scene;
  94044. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  94045. this._pointerObserver = null;
  94046. this._attachedMesh = null;
  94047. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  94048. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  94049. /**
  94050. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  94051. */
  94052. this.attachableMeshes = null;
  94053. /**
  94054. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  94055. */
  94056. this.usePointerToAttachGizmos = true;
  94057. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  94058. // Instatiate/dispose gizmos based on pointer actions
  94059. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  94060. if (!_this.usePointerToAttachGizmos) {
  94061. return;
  94062. }
  94063. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94064. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  94065. var node = pointerInfo.pickInfo.pickedMesh;
  94066. if (_this.attachableMeshes == null) {
  94067. // Attach to the most parent node
  94068. while (node && node.parent != null) {
  94069. node = node.parent;
  94070. }
  94071. }
  94072. else {
  94073. // Attach to the parent node that is an attachableMesh
  94074. var found = false;
  94075. _this.attachableMeshes.forEach(function (mesh) {
  94076. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  94077. node = mesh;
  94078. found = true;
  94079. }
  94080. });
  94081. if (!found) {
  94082. node = null;
  94083. }
  94084. }
  94085. if (node instanceof BABYLON.AbstractMesh) {
  94086. _this.attachToMesh(node);
  94087. }
  94088. else {
  94089. _this.attachToMesh(null);
  94090. }
  94091. }
  94092. else {
  94093. _this.attachToMesh(null);
  94094. }
  94095. }
  94096. });
  94097. }
  94098. /**
  94099. * Attaches a set of gizmos to the specified mesh
  94100. * @param mesh The mesh the gizmo's should be attached to
  94101. */
  94102. GizmoManager.prototype.attachToMesh = function (mesh) {
  94103. if (this._attachedMesh) {
  94104. this._attachedMesh.removeBehavior(this._dragBehavior);
  94105. }
  94106. this._attachedMesh = mesh;
  94107. for (var key in this.gizmos) {
  94108. var gizmo = (this.gizmos[key]);
  94109. if (gizmo && this._gizmosEnabled[key]) {
  94110. gizmo.attachedMesh = mesh;
  94111. }
  94112. }
  94113. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  94114. this._attachedMesh.addBehavior(this._dragBehavior);
  94115. }
  94116. };
  94117. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  94118. get: function () {
  94119. return this._gizmosEnabled.positionGizmo;
  94120. },
  94121. /**
  94122. * If the position gizmo is enabled
  94123. */
  94124. set: function (value) {
  94125. if (value) {
  94126. if (!this.gizmos.positionGizmo) {
  94127. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  94128. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94129. }
  94130. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  94131. }
  94132. else if (this.gizmos.positionGizmo) {
  94133. this.gizmos.positionGizmo.attachedMesh = null;
  94134. }
  94135. this._gizmosEnabled.positionGizmo = value;
  94136. },
  94137. enumerable: true,
  94138. configurable: true
  94139. });
  94140. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  94141. get: function () {
  94142. return this._gizmosEnabled.rotationGizmo;
  94143. },
  94144. /**
  94145. * If the rotation gizmo is enabled
  94146. */
  94147. set: function (value) {
  94148. if (value) {
  94149. if (!this.gizmos.rotationGizmo) {
  94150. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  94151. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94152. }
  94153. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  94154. }
  94155. else if (this.gizmos.rotationGizmo) {
  94156. this.gizmos.rotationGizmo.attachedMesh = null;
  94157. }
  94158. this._gizmosEnabled.rotationGizmo = value;
  94159. },
  94160. enumerable: true,
  94161. configurable: true
  94162. });
  94163. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  94164. get: function () {
  94165. return this._gizmosEnabled.scaleGizmo;
  94166. },
  94167. /**
  94168. * If the scale gizmo is enabled
  94169. */
  94170. set: function (value) {
  94171. if (value) {
  94172. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  94173. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  94174. }
  94175. else if (this.gizmos.scaleGizmo) {
  94176. this.gizmos.scaleGizmo.attachedMesh = null;
  94177. }
  94178. this._gizmosEnabled.scaleGizmo = value;
  94179. },
  94180. enumerable: true,
  94181. configurable: true
  94182. });
  94183. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  94184. get: function () {
  94185. return this._gizmosEnabled.boundingBoxGizmo;
  94186. },
  94187. /**
  94188. * If the boundingBox gizmo is enabled
  94189. */
  94190. set: function (value) {
  94191. if (value) {
  94192. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  94193. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  94194. if (this._attachedMesh) {
  94195. this._attachedMesh.removeBehavior(this._dragBehavior);
  94196. this._attachedMesh.addBehavior(this._dragBehavior);
  94197. }
  94198. }
  94199. else if (this.gizmos.boundingBoxGizmo) {
  94200. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  94201. }
  94202. this._gizmosEnabled.boundingBoxGizmo = value;
  94203. },
  94204. enumerable: true,
  94205. configurable: true
  94206. });
  94207. /**
  94208. * Disposes of the gizmo manager
  94209. */
  94210. GizmoManager.prototype.dispose = function () {
  94211. this.scene.onPointerObservable.remove(this._pointerObserver);
  94212. for (var key in this.gizmos) {
  94213. var gizmo = (this.gizmos[key]);
  94214. if (gizmo) {
  94215. gizmo.dispose();
  94216. }
  94217. }
  94218. this._dragBehavior.detach();
  94219. };
  94220. return GizmoManager;
  94221. }());
  94222. BABYLON.GizmoManager = GizmoManager;
  94223. })(BABYLON || (BABYLON = {}));
  94224. //# sourceMappingURL=babylon.gizmoManager.js.map
  94225. var BABYLON;
  94226. (function (BABYLON) {
  94227. /**
  94228. * Defines a target to use with MorphTargetManager
  94229. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94230. */
  94231. var MorphTarget = /** @class */ (function () {
  94232. /**
  94233. * Creates a new MorphTarget
  94234. * @param name defines the name of the target
  94235. * @param influence defines the influence to use
  94236. */
  94237. function MorphTarget(
  94238. /** defines the name of the target */
  94239. name, influence, scene) {
  94240. if (influence === void 0) { influence = 0; }
  94241. if (scene === void 0) { scene = null; }
  94242. this.name = name;
  94243. /**
  94244. * Gets or sets the list of animations
  94245. */
  94246. this.animations = new Array();
  94247. this._positions = null;
  94248. this._normals = null;
  94249. this._tangents = null;
  94250. /**
  94251. * Observable raised when the influence changes
  94252. */
  94253. this.onInfluenceChanged = new BABYLON.Observable();
  94254. this._animationPropertiesOverride = null;
  94255. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94256. this.influence = influence;
  94257. }
  94258. Object.defineProperty(MorphTarget.prototype, "influence", {
  94259. /**
  94260. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  94261. */
  94262. get: function () {
  94263. return this._influence;
  94264. },
  94265. set: function (influence) {
  94266. if (this._influence === influence) {
  94267. return;
  94268. }
  94269. var previous = this._influence;
  94270. this._influence = influence;
  94271. if (this.onInfluenceChanged.hasObservers) {
  94272. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  94273. }
  94274. },
  94275. enumerable: true,
  94276. configurable: true
  94277. });
  94278. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  94279. /**
  94280. * Gets or sets the animation properties override
  94281. */
  94282. get: function () {
  94283. if (!this._animationPropertiesOverride && this._scene) {
  94284. return this._scene.animationPropertiesOverride;
  94285. }
  94286. return this._animationPropertiesOverride;
  94287. },
  94288. set: function (value) {
  94289. this._animationPropertiesOverride = value;
  94290. },
  94291. enumerable: true,
  94292. configurable: true
  94293. });
  94294. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  94295. /**
  94296. * Gets a boolean defining if the target contains position data
  94297. */
  94298. get: function () {
  94299. return !!this._positions;
  94300. },
  94301. enumerable: true,
  94302. configurable: true
  94303. });
  94304. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  94305. /**
  94306. * Gets a boolean defining if the target contains normal data
  94307. */
  94308. get: function () {
  94309. return !!this._normals;
  94310. },
  94311. enumerable: true,
  94312. configurable: true
  94313. });
  94314. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  94315. /**
  94316. * Gets a boolean defining if the target contains tangent data
  94317. */
  94318. get: function () {
  94319. return !!this._tangents;
  94320. },
  94321. enumerable: true,
  94322. configurable: true
  94323. });
  94324. /**
  94325. * Affects position data to this target
  94326. * @param data defines the position data to use
  94327. */
  94328. MorphTarget.prototype.setPositions = function (data) {
  94329. this._positions = data;
  94330. };
  94331. /**
  94332. * Gets the position data stored in this target
  94333. * @returns a FloatArray containing the position data (or null if not present)
  94334. */
  94335. MorphTarget.prototype.getPositions = function () {
  94336. return this._positions;
  94337. };
  94338. /**
  94339. * Affects normal data to this target
  94340. * @param data defines the normal data to use
  94341. */
  94342. MorphTarget.prototype.setNormals = function (data) {
  94343. this._normals = data;
  94344. };
  94345. /**
  94346. * Gets the normal data stored in this target
  94347. * @returns a FloatArray containing the normal data (or null if not present)
  94348. */
  94349. MorphTarget.prototype.getNormals = function () {
  94350. return this._normals;
  94351. };
  94352. /**
  94353. * Affects tangent data to this target
  94354. * @param data defines the tangent data to use
  94355. */
  94356. MorphTarget.prototype.setTangents = function (data) {
  94357. this._tangents = data;
  94358. };
  94359. /**
  94360. * Gets the tangent data stored in this target
  94361. * @returns a FloatArray containing the tangent data (or null if not present)
  94362. */
  94363. MorphTarget.prototype.getTangents = function () {
  94364. return this._tangents;
  94365. };
  94366. /**
  94367. * Serializes the current target into a Serialization object
  94368. * @returns the serialized object
  94369. */
  94370. MorphTarget.prototype.serialize = function () {
  94371. var serializationObject = {};
  94372. serializationObject.name = this.name;
  94373. serializationObject.influence = this.influence;
  94374. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  94375. if (this.hasNormals) {
  94376. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  94377. }
  94378. if (this.hasTangents) {
  94379. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  94380. }
  94381. // Animations
  94382. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  94383. return serializationObject;
  94384. };
  94385. // Statics
  94386. /**
  94387. * Creates a new target from serialized data
  94388. * @param serializationObject defines the serialized data to use
  94389. * @returns a new MorphTarget
  94390. */
  94391. MorphTarget.Parse = function (serializationObject) {
  94392. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  94393. result.setPositions(serializationObject.positions);
  94394. if (serializationObject.normals) {
  94395. result.setNormals(serializationObject.normals);
  94396. }
  94397. if (serializationObject.tangents) {
  94398. result.setTangents(serializationObject.tangents);
  94399. }
  94400. // Animations
  94401. if (serializationObject.animations) {
  94402. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  94403. var parsedAnimation = serializationObject.animations[animationIndex];
  94404. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  94405. }
  94406. }
  94407. return result;
  94408. };
  94409. /**
  94410. * Creates a MorphTarget from mesh data
  94411. * @param mesh defines the source mesh
  94412. * @param name defines the name to use for the new target
  94413. * @param influence defines the influence to attach to the target
  94414. * @returns a new MorphTarget
  94415. */
  94416. MorphTarget.FromMesh = function (mesh, name, influence) {
  94417. if (!name) {
  94418. name = mesh.name;
  94419. }
  94420. var result = new MorphTarget(name, influence, mesh.getScene());
  94421. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94422. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  94423. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  94424. }
  94425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  94426. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  94427. }
  94428. return result;
  94429. };
  94430. return MorphTarget;
  94431. }());
  94432. BABYLON.MorphTarget = MorphTarget;
  94433. })(BABYLON || (BABYLON = {}));
  94434. //# sourceMappingURL=babylon.morphTarget.js.map
  94435. var BABYLON;
  94436. (function (BABYLON) {
  94437. /**
  94438. * This class is used to deform meshes using morphing between different targets
  94439. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94440. */
  94441. var MorphTargetManager = /** @class */ (function () {
  94442. /**
  94443. * Creates a new MorphTargetManager
  94444. * @param scene defines the current scene
  94445. */
  94446. function MorphTargetManager(scene) {
  94447. if (scene === void 0) { scene = null; }
  94448. this._targets = new Array();
  94449. this._targetObservable = new Array();
  94450. this._activeTargets = new BABYLON.SmartArray(16);
  94451. this._supportsNormals = false;
  94452. this._supportsTangents = false;
  94453. this._vertexCount = 0;
  94454. this._uniqueId = 0;
  94455. this._tempInfluences = new Array();
  94456. if (!scene) {
  94457. scene = BABYLON.Engine.LastCreatedScene;
  94458. }
  94459. this._scene = scene;
  94460. if (this._scene) {
  94461. this._scene.morphTargetManagers.push(this);
  94462. this._uniqueId = this._scene.getUniqueId();
  94463. }
  94464. }
  94465. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  94466. /**
  94467. * Gets the unique ID of this manager
  94468. */
  94469. get: function () {
  94470. return this._uniqueId;
  94471. },
  94472. enumerable: true,
  94473. configurable: true
  94474. });
  94475. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  94476. /**
  94477. * Gets the number of vertices handled by this manager
  94478. */
  94479. get: function () {
  94480. return this._vertexCount;
  94481. },
  94482. enumerable: true,
  94483. configurable: true
  94484. });
  94485. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  94486. /**
  94487. * Gets a boolean indicating if this manager supports morphing of normals
  94488. */
  94489. get: function () {
  94490. return this._supportsNormals;
  94491. },
  94492. enumerable: true,
  94493. configurable: true
  94494. });
  94495. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  94496. /**
  94497. * Gets a boolean indicating if this manager supports morphing of tangents
  94498. */
  94499. get: function () {
  94500. return this._supportsTangents;
  94501. },
  94502. enumerable: true,
  94503. configurable: true
  94504. });
  94505. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  94506. /**
  94507. * Gets the number of targets stored in this manager
  94508. */
  94509. get: function () {
  94510. return this._targets.length;
  94511. },
  94512. enumerable: true,
  94513. configurable: true
  94514. });
  94515. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  94516. /**
  94517. * Gets the number of influencers (ie. the number of targets with influences > 0)
  94518. */
  94519. get: function () {
  94520. return this._activeTargets.length;
  94521. },
  94522. enumerable: true,
  94523. configurable: true
  94524. });
  94525. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  94526. /**
  94527. * Gets the list of influences (one per target)
  94528. */
  94529. get: function () {
  94530. return this._influences;
  94531. },
  94532. enumerable: true,
  94533. configurable: true
  94534. });
  94535. /**
  94536. * Gets the active target at specified index. An active target is a target with an influence > 0
  94537. * @param index defines the index to check
  94538. * @returns the requested target
  94539. */
  94540. MorphTargetManager.prototype.getActiveTarget = function (index) {
  94541. return this._activeTargets.data[index];
  94542. };
  94543. /**
  94544. * Gets the target at specified index
  94545. * @param index defines the index to check
  94546. * @returns the requested target
  94547. */
  94548. MorphTargetManager.prototype.getTarget = function (index) {
  94549. return this._targets[index];
  94550. };
  94551. /**
  94552. * Add a new target to this manager
  94553. * @param target defines the target to add
  94554. */
  94555. MorphTargetManager.prototype.addTarget = function (target) {
  94556. var _this = this;
  94557. this._targets.push(target);
  94558. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  94559. _this._syncActiveTargets(needUpdate);
  94560. }));
  94561. this._syncActiveTargets(true);
  94562. };
  94563. /**
  94564. * Removes a target from the manager
  94565. * @param target defines the target to remove
  94566. */
  94567. MorphTargetManager.prototype.removeTarget = function (target) {
  94568. var index = this._targets.indexOf(target);
  94569. if (index >= 0) {
  94570. this._targets.splice(index, 1);
  94571. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  94572. this._syncActiveTargets(true);
  94573. }
  94574. };
  94575. /**
  94576. * Serializes the current manager into a Serialization object
  94577. * @returns the serialized object
  94578. */
  94579. MorphTargetManager.prototype.serialize = function () {
  94580. var serializationObject = {};
  94581. serializationObject.id = this.uniqueId;
  94582. serializationObject.targets = [];
  94583. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94584. var target = _a[_i];
  94585. serializationObject.targets.push(target.serialize());
  94586. }
  94587. return serializationObject;
  94588. };
  94589. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  94590. var influenceCount = 0;
  94591. this._activeTargets.reset();
  94592. this._supportsNormals = true;
  94593. this._supportsTangents = true;
  94594. this._vertexCount = 0;
  94595. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94596. var target = _a[_i];
  94597. this._activeTargets.push(target);
  94598. this._tempInfluences[influenceCount++] = target.influence;
  94599. var positions = target.getPositions();
  94600. if (positions) {
  94601. this._supportsNormals = this._supportsNormals && target.hasNormals;
  94602. this._supportsTangents = this._supportsTangents && target.hasTangents;
  94603. var vertexCount = positions.length / 3;
  94604. if (this._vertexCount === 0) {
  94605. this._vertexCount = vertexCount;
  94606. }
  94607. else if (this._vertexCount !== vertexCount) {
  94608. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  94609. return;
  94610. }
  94611. }
  94612. }
  94613. if (!this._influences || this._influences.length !== influenceCount) {
  94614. this._influences = new Float32Array(influenceCount);
  94615. }
  94616. for (var index = 0; index < influenceCount; index++) {
  94617. this._influences[index] = this._tempInfluences[index];
  94618. }
  94619. if (needUpdate) {
  94620. this.synchronize();
  94621. }
  94622. };
  94623. /**
  94624. * Syncrhonize the targets with all the meshes using this morph target manager
  94625. */
  94626. MorphTargetManager.prototype.synchronize = function () {
  94627. if (!this._scene) {
  94628. return;
  94629. }
  94630. // Flag meshes as dirty to resync with the active targets
  94631. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  94632. var mesh = _a[_i];
  94633. if (mesh.morphTargetManager === this) {
  94634. mesh._syncGeometryWithMorphTargetManager();
  94635. }
  94636. }
  94637. };
  94638. // Statics
  94639. /**
  94640. * Creates a new MorphTargetManager from serialized data
  94641. * @param serializationObject defines the serialized data
  94642. * @param scene defines the hosting scene
  94643. * @returns the new MorphTargetManager
  94644. */
  94645. MorphTargetManager.Parse = function (serializationObject, scene) {
  94646. var result = new MorphTargetManager(scene);
  94647. result._uniqueId = serializationObject.id;
  94648. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  94649. var targetData = _a[_i];
  94650. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  94651. }
  94652. return result;
  94653. };
  94654. return MorphTargetManager;
  94655. }());
  94656. BABYLON.MorphTargetManager = MorphTargetManager;
  94657. })(BABYLON || (BABYLON = {}));
  94658. //# sourceMappingURL=babylon.morphTargetManager.js.map
  94659. var BABYLON;
  94660. (function (BABYLON) {
  94661. var Octree = /** @class */ (function () {
  94662. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  94663. if (maxDepth === void 0) { maxDepth = 2; }
  94664. this.maxDepth = maxDepth;
  94665. this.dynamicContent = new Array();
  94666. this._maxBlockCapacity = maxBlockCapacity || 64;
  94667. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  94668. this._creationFunc = creationFunc;
  94669. }
  94670. // Methods
  94671. Octree.prototype.update = function (worldMin, worldMax, entries) {
  94672. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  94673. };
  94674. Octree.prototype.addMesh = function (entry) {
  94675. for (var index = 0; index < this.blocks.length; index++) {
  94676. var block = this.blocks[index];
  94677. block.addEntry(entry);
  94678. }
  94679. };
  94680. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  94681. this._selectionContent.reset();
  94682. for (var index = 0; index < this.blocks.length; index++) {
  94683. var block = this.blocks[index];
  94684. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  94685. }
  94686. if (allowDuplicate) {
  94687. this._selectionContent.concat(this.dynamicContent);
  94688. }
  94689. else {
  94690. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94691. }
  94692. return this._selectionContent;
  94693. };
  94694. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  94695. this._selectionContent.reset();
  94696. for (var index = 0; index < this.blocks.length; index++) {
  94697. var block = this.blocks[index];
  94698. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  94699. }
  94700. if (allowDuplicate) {
  94701. this._selectionContent.concat(this.dynamicContent);
  94702. }
  94703. else {
  94704. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94705. }
  94706. return this._selectionContent;
  94707. };
  94708. Octree.prototype.intersectsRay = function (ray) {
  94709. this._selectionContent.reset();
  94710. for (var index = 0; index < this.blocks.length; index++) {
  94711. var block = this.blocks[index];
  94712. block.intersectsRay(ray, this._selectionContent);
  94713. }
  94714. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94715. return this._selectionContent;
  94716. };
  94717. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94718. target.blocks = new Array();
  94719. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94720. // Segmenting space
  94721. for (var x = 0; x < 2; x++) {
  94722. for (var y = 0; y < 2; y++) {
  94723. for (var z = 0; z < 2; z++) {
  94724. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94725. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94726. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94727. block.addEntries(entries);
  94728. target.blocks.push(block);
  94729. }
  94730. }
  94731. }
  94732. };
  94733. Octree.CreationFuncForMeshes = function (entry, block) {
  94734. var boundingInfo = entry.getBoundingInfo();
  94735. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94736. block.entries.push(entry);
  94737. }
  94738. };
  94739. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94740. var boundingInfo = entry.getBoundingInfo();
  94741. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94742. block.entries.push(entry);
  94743. }
  94744. };
  94745. return Octree;
  94746. }());
  94747. BABYLON.Octree = Octree;
  94748. })(BABYLON || (BABYLON = {}));
  94749. //# sourceMappingURL=babylon.octree.js.map
  94750. var BABYLON;
  94751. (function (BABYLON) {
  94752. var OctreeBlock = /** @class */ (function () {
  94753. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94754. this.entries = new Array();
  94755. this._boundingVectors = new Array();
  94756. this._capacity = capacity;
  94757. this._depth = depth;
  94758. this._maxDepth = maxDepth;
  94759. this._creationFunc = creationFunc;
  94760. this._minPoint = minPoint;
  94761. this._maxPoint = maxPoint;
  94762. this._boundingVectors.push(minPoint.clone());
  94763. this._boundingVectors.push(maxPoint.clone());
  94764. this._boundingVectors.push(minPoint.clone());
  94765. this._boundingVectors[2].x = maxPoint.x;
  94766. this._boundingVectors.push(minPoint.clone());
  94767. this._boundingVectors[3].y = maxPoint.y;
  94768. this._boundingVectors.push(minPoint.clone());
  94769. this._boundingVectors[4].z = maxPoint.z;
  94770. this._boundingVectors.push(maxPoint.clone());
  94771. this._boundingVectors[5].z = minPoint.z;
  94772. this._boundingVectors.push(maxPoint.clone());
  94773. this._boundingVectors[6].x = minPoint.x;
  94774. this._boundingVectors.push(maxPoint.clone());
  94775. this._boundingVectors[7].y = minPoint.y;
  94776. }
  94777. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94778. // Property
  94779. get: function () {
  94780. return this._capacity;
  94781. },
  94782. enumerable: true,
  94783. configurable: true
  94784. });
  94785. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  94786. get: function () {
  94787. return this._minPoint;
  94788. },
  94789. enumerable: true,
  94790. configurable: true
  94791. });
  94792. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  94793. get: function () {
  94794. return this._maxPoint;
  94795. },
  94796. enumerable: true,
  94797. configurable: true
  94798. });
  94799. // Methods
  94800. OctreeBlock.prototype.addEntry = function (entry) {
  94801. if (this.blocks) {
  94802. for (var index = 0; index < this.blocks.length; index++) {
  94803. var block = this.blocks[index];
  94804. block.addEntry(entry);
  94805. }
  94806. return;
  94807. }
  94808. this._creationFunc(entry, this);
  94809. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  94810. this.createInnerBlocks();
  94811. }
  94812. };
  94813. OctreeBlock.prototype.addEntries = function (entries) {
  94814. for (var index = 0; index < entries.length; index++) {
  94815. var mesh = entries[index];
  94816. this.addEntry(mesh);
  94817. }
  94818. };
  94819. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  94820. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  94821. if (this.blocks) {
  94822. for (var index = 0; index < this.blocks.length; index++) {
  94823. var block = this.blocks[index];
  94824. block.select(frustumPlanes, selection, allowDuplicate);
  94825. }
  94826. return;
  94827. }
  94828. if (allowDuplicate) {
  94829. selection.concat(this.entries);
  94830. }
  94831. else {
  94832. selection.concatWithNoDuplicate(this.entries);
  94833. }
  94834. }
  94835. };
  94836. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  94837. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  94838. if (this.blocks) {
  94839. for (var index = 0; index < this.blocks.length; index++) {
  94840. var block = this.blocks[index];
  94841. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  94842. }
  94843. return;
  94844. }
  94845. if (allowDuplicate) {
  94846. selection.concat(this.entries);
  94847. }
  94848. else {
  94849. selection.concatWithNoDuplicate(this.entries);
  94850. }
  94851. }
  94852. };
  94853. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  94854. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  94855. if (this.blocks) {
  94856. for (var index = 0; index < this.blocks.length; index++) {
  94857. var block = this.blocks[index];
  94858. block.intersectsRay(ray, selection);
  94859. }
  94860. return;
  94861. }
  94862. selection.concatWithNoDuplicate(this.entries);
  94863. }
  94864. };
  94865. OctreeBlock.prototype.createInnerBlocks = function () {
  94866. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  94867. };
  94868. return OctreeBlock;
  94869. }());
  94870. BABYLON.OctreeBlock = OctreeBlock;
  94871. })(BABYLON || (BABYLON = {}));
  94872. //# sourceMappingURL=babylon.octreeBlock.js.map
  94873. var BABYLON;
  94874. (function (BABYLON) {
  94875. /**
  94876. * Postprocess used to generate anaglyphic rendering
  94877. */
  94878. var AnaglyphPostProcess = /** @class */ (function (_super) {
  94879. __extends(AnaglyphPostProcess, _super);
  94880. /**
  94881. * Creates a new AnaglyphPostProcess
  94882. * @param name defines postprocess name
  94883. * @param options defines creation options or target ratio scale
  94884. * @param rigCameras defines cameras using this postprocess
  94885. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  94886. * @param engine defines hosting engine
  94887. * @param reusable defines if the postprocess will be reused multiple times per frame
  94888. */
  94889. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  94890. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  94891. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94892. _this.onApplyObservable.add(function (effect) {
  94893. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  94894. });
  94895. return _this;
  94896. }
  94897. return AnaglyphPostProcess;
  94898. }(BABYLON.PostProcess));
  94899. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  94900. })(BABYLON || (BABYLON = {}));
  94901. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  94902. var BABYLON;
  94903. (function (BABYLON) {
  94904. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  94905. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94906. });
  94907. /**
  94908. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  94909. */
  94910. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  94911. __extends(AnaglyphArcRotateCamera, _super);
  94912. /**
  94913. * Creates a new AnaglyphArcRotateCamera
  94914. * @param name defines camera name
  94915. * @param alpha defines alpha angle (in radians)
  94916. * @param beta defines beta angle (in radians)
  94917. * @param radius defines radius
  94918. * @param target defines camera target
  94919. * @param interaxialDistance defines distance between each color axis
  94920. * @param scene defines the hosting scene
  94921. */
  94922. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  94923. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94924. _this.interaxialDistance = interaxialDistance;
  94925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94926. return _this;
  94927. }
  94928. /**
  94929. * Gets camera class name
  94930. * @returns AnaglyphArcRotateCamera
  94931. */
  94932. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  94933. return "AnaglyphArcRotateCamera";
  94934. };
  94935. return AnaglyphArcRotateCamera;
  94936. }(BABYLON.ArcRotateCamera));
  94937. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  94938. })(BABYLON || (BABYLON = {}));
  94939. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  94940. var BABYLON;
  94941. (function (BABYLON) {
  94942. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  94943. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94944. });
  94945. /**
  94946. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  94947. */
  94948. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  94949. __extends(AnaglyphFreeCamera, _super);
  94950. /**
  94951. * Creates a new AnaglyphFreeCamera
  94952. * @param name defines camera name
  94953. * @param position defines initial position
  94954. * @param interaxialDistance defines distance between each color axis
  94955. * @param scene defines the hosting scene
  94956. */
  94957. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  94958. var _this = _super.call(this, name, position, scene) || this;
  94959. _this.interaxialDistance = interaxialDistance;
  94960. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94961. return _this;
  94962. }
  94963. /**
  94964. * Gets camera class name
  94965. * @returns AnaglyphFreeCamera
  94966. */
  94967. AnaglyphFreeCamera.prototype.getClassName = function () {
  94968. return "AnaglyphFreeCamera";
  94969. };
  94970. return AnaglyphFreeCamera;
  94971. }(BABYLON.FreeCamera));
  94972. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  94973. })(BABYLON || (BABYLON = {}));
  94974. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  94975. var BABYLON;
  94976. (function (BABYLON) {
  94977. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  94978. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94979. });
  94980. /**
  94981. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  94982. */
  94983. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  94984. __extends(AnaglyphGamepadCamera, _super);
  94985. /**
  94986. * Creates a new AnaglyphGamepadCamera
  94987. * @param name defines camera name
  94988. * @param position defines initial position
  94989. * @param interaxialDistance defines distance between each color axis
  94990. * @param scene defines the hosting scene
  94991. */
  94992. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  94993. var _this = _super.call(this, name, position, scene) || this;
  94994. _this.interaxialDistance = interaxialDistance;
  94995. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94996. return _this;
  94997. }
  94998. /**
  94999. * Gets camera class name
  95000. * @returns AnaglyphGamepadCamera
  95001. */
  95002. AnaglyphGamepadCamera.prototype.getClassName = function () {
  95003. return "AnaglyphGamepadCamera";
  95004. };
  95005. return AnaglyphGamepadCamera;
  95006. }(BABYLON.GamepadCamera));
  95007. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  95008. })(BABYLON || (BABYLON = {}));
  95009. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  95010. var BABYLON;
  95011. (function (BABYLON) {
  95012. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  95013. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95014. });
  95015. /**
  95016. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  95017. */
  95018. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  95019. __extends(AnaglyphUniversalCamera, _super);
  95020. /**
  95021. * Creates a new AnaglyphUniversalCamera
  95022. * @param name defines camera name
  95023. * @param position defines initial position
  95024. * @param interaxialDistance defines distance between each color axis
  95025. * @param scene defines the hosting scene
  95026. */
  95027. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  95028. var _this = _super.call(this, name, position, scene) || this;
  95029. _this.interaxialDistance = interaxialDistance;
  95030. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95031. return _this;
  95032. }
  95033. /**
  95034. * Gets camera class name
  95035. * @returns AnaglyphUniversalCamera
  95036. */
  95037. AnaglyphUniversalCamera.prototype.getClassName = function () {
  95038. return "AnaglyphUniversalCamera";
  95039. };
  95040. return AnaglyphUniversalCamera;
  95041. }(BABYLON.UniversalCamera));
  95042. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  95043. })(BABYLON || (BABYLON = {}));
  95044. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  95045. var BABYLON;
  95046. (function (BABYLON) {
  95047. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  95048. __extends(StereoscopicInterlacePostProcess, _super);
  95049. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  95050. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  95051. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95052. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95053. _this.onSizeChangedObservable.add(function () {
  95054. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95055. });
  95056. _this.onApplyObservable.add(function (effect) {
  95057. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  95058. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  95059. });
  95060. return _this;
  95061. }
  95062. return StereoscopicInterlacePostProcess;
  95063. }(BABYLON.PostProcess));
  95064. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  95065. })(BABYLON || (BABYLON = {}));
  95066. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  95067. var BABYLON;
  95068. (function (BABYLON) {
  95069. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  95070. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95071. });
  95072. /**
  95073. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  95074. */
  95075. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  95076. __extends(StereoscopicArcRotateCamera, _super);
  95077. /**
  95078. * Creates a new StereoscopicArcRotateCamera
  95079. * @param name defines camera name
  95080. * @param alpha defines alpha angle (in radians)
  95081. * @param beta defines beta angle (in radians)
  95082. * @param radius defines radius
  95083. * @param target defines camera target
  95084. * @param interaxialDistance defines distance between each color axis
  95085. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95086. * @param scene defines the hosting scene
  95087. */
  95088. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  95089. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95090. _this.interaxialDistance = interaxialDistance;
  95091. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95092. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95093. return _this;
  95094. }
  95095. /**
  95096. * Gets camera class name
  95097. * @returns StereoscopicArcRotateCamera
  95098. */
  95099. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  95100. return "StereoscopicArcRotateCamera";
  95101. };
  95102. return StereoscopicArcRotateCamera;
  95103. }(BABYLON.ArcRotateCamera));
  95104. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  95105. })(BABYLON || (BABYLON = {}));
  95106. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  95107. var BABYLON;
  95108. (function (BABYLON) {
  95109. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  95110. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95111. });
  95112. /**
  95113. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  95114. */
  95115. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  95116. __extends(StereoscopicFreeCamera, _super);
  95117. /**
  95118. * Creates a new StereoscopicFreeCamera
  95119. * @param name defines camera name
  95120. * @param position defines initial position
  95121. * @param interaxialDistance defines distance between each color axis
  95122. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95123. * @param scene defines the hosting scene
  95124. */
  95125. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95126. var _this = _super.call(this, name, position, scene) || this;
  95127. _this.interaxialDistance = interaxialDistance;
  95128. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95129. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95130. return _this;
  95131. }
  95132. /**
  95133. * Gets camera class name
  95134. * @returns StereoscopicFreeCamera
  95135. */
  95136. StereoscopicFreeCamera.prototype.getClassName = function () {
  95137. return "StereoscopicFreeCamera";
  95138. };
  95139. return StereoscopicFreeCamera;
  95140. }(BABYLON.FreeCamera));
  95141. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  95142. })(BABYLON || (BABYLON = {}));
  95143. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  95144. var BABYLON;
  95145. (function (BABYLON) {
  95146. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  95147. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95148. });
  95149. /**
  95150. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  95151. */
  95152. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  95153. __extends(StereoscopicGamepadCamera, _super);
  95154. /**
  95155. * Creates a new StereoscopicGamepadCamera
  95156. * @param name defines camera name
  95157. * @param position defines initial position
  95158. * @param interaxialDistance defines distance between each color axis
  95159. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95160. * @param scene defines the hosting scene
  95161. */
  95162. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95163. var _this = _super.call(this, name, position, scene) || this;
  95164. _this.interaxialDistance = interaxialDistance;
  95165. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95166. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95167. return _this;
  95168. }
  95169. /**
  95170. * Gets camera class name
  95171. * @returns StereoscopicGamepadCamera
  95172. */
  95173. StereoscopicGamepadCamera.prototype.getClassName = function () {
  95174. return "StereoscopicGamepadCamera";
  95175. };
  95176. return StereoscopicGamepadCamera;
  95177. }(BABYLON.GamepadCamera));
  95178. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  95179. })(BABYLON || (BABYLON = {}));
  95180. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  95181. var BABYLON;
  95182. (function (BABYLON) {
  95183. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  95184. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95185. });
  95186. /**
  95187. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  95188. */
  95189. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  95190. __extends(StereoscopicUniversalCamera, _super);
  95191. /**
  95192. * Creates a new StereoscopicUniversalCamera
  95193. * @param name defines camera name
  95194. * @param position defines initial position
  95195. * @param interaxialDistance defines distance between each color axis
  95196. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95197. * @param scene defines the hosting scene
  95198. */
  95199. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95200. var _this = _super.call(this, name, position, scene) || this;
  95201. _this.interaxialDistance = interaxialDistance;
  95202. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95203. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95204. return _this;
  95205. }
  95206. /**
  95207. * Gets camera class name
  95208. * @returns StereoscopicUniversalCamera
  95209. */
  95210. StereoscopicUniversalCamera.prototype.getClassName = function () {
  95211. return "StereoscopicUniversalCamera";
  95212. };
  95213. return StereoscopicUniversalCamera;
  95214. }(BABYLON.UniversalCamera));
  95215. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  95216. })(BABYLON || (BABYLON = {}));
  95217. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  95218. var BABYLON;
  95219. (function (BABYLON) {
  95220. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  95221. __extends(VRDistortionCorrectionPostProcess, _super);
  95222. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  95223. var _this = _super.call(this, name, "vrDistortionCorrection", [
  95224. 'LensCenter',
  95225. 'Scale',
  95226. 'ScaleIn',
  95227. 'HmdWarpParam'
  95228. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  95229. _this._isRightEye = isRightEye;
  95230. _this._distortionFactors = vrMetrics.distortionK;
  95231. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  95232. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  95233. _this.adaptScaleToCurrentViewport = true;
  95234. _this.onSizeChangedObservable.add(function () {
  95235. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  95236. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  95237. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  95238. });
  95239. _this.onApplyObservable.add(function (effect) {
  95240. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  95241. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  95242. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  95243. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  95244. });
  95245. return _this;
  95246. }
  95247. return VRDistortionCorrectionPostProcess;
  95248. }(BABYLON.PostProcess));
  95249. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  95250. })(BABYLON || (BABYLON = {}));
  95251. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  95252. var BABYLON;
  95253. (function (BABYLON) {
  95254. /**
  95255. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  95256. * Screen rotation is taken into account.
  95257. */
  95258. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  95259. function FreeCameraDeviceOrientationInput() {
  95260. var _this = this;
  95261. this._screenOrientationAngle = 0;
  95262. this._screenQuaternion = new BABYLON.Quaternion();
  95263. this._alpha = 0;
  95264. this._beta = 0;
  95265. this._gamma = 0;
  95266. this._orientationChanged = function () {
  95267. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  95268. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  95269. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  95270. };
  95271. this._deviceOrientation = function (evt) {
  95272. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  95273. _this._beta = evt.beta !== null ? evt.beta : 0;
  95274. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  95275. };
  95276. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  95277. this._orientationChanged();
  95278. }
  95279. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  95280. get: function () {
  95281. return this._camera;
  95282. },
  95283. set: function (camera) {
  95284. this._camera = camera;
  95285. if (this._camera != null && !this._camera.rotationQuaternion) {
  95286. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  95287. }
  95288. },
  95289. enumerable: true,
  95290. configurable: true
  95291. });
  95292. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  95293. window.addEventListener("orientationchange", this._orientationChanged);
  95294. window.addEventListener("deviceorientation", this._deviceOrientation);
  95295. //In certain cases, the attach control is called AFTER orientation was changed,
  95296. //So this is needed.
  95297. this._orientationChanged();
  95298. };
  95299. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  95300. window.removeEventListener("orientationchange", this._orientationChanged);
  95301. window.removeEventListener("deviceorientation", this._deviceOrientation);
  95302. };
  95303. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  95304. //if no device orientation provided, don't update the rotation.
  95305. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  95306. if (!this._alpha)
  95307. return;
  95308. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  95309. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  95310. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  95311. //Mirror on XY Plane
  95312. this._camera.rotationQuaternion.z *= -1;
  95313. this._camera.rotationQuaternion.w *= -1;
  95314. };
  95315. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  95316. return "FreeCameraDeviceOrientationInput";
  95317. };
  95318. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  95319. return "deviceOrientation";
  95320. };
  95321. return FreeCameraDeviceOrientationInput;
  95322. }());
  95323. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  95324. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  95325. })(BABYLON || (BABYLON = {}));
  95326. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  95327. var BABYLON;
  95328. (function (BABYLON) {
  95329. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  95330. function ArcRotateCameraVRDeviceOrientationInput() {
  95331. this.alphaCorrection = 1;
  95332. this.betaCorrection = 1;
  95333. this.gammaCorrection = 1;
  95334. this._alpha = 0;
  95335. this._gamma = 0;
  95336. this._dirty = false;
  95337. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  95338. }
  95339. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  95340. this.camera.attachControl(element, noPreventDefault);
  95341. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  95342. };
  95343. /** @hidden */
  95344. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  95345. if (evt.alpha !== null) {
  95346. this._alpha = +evt.alpha | 0;
  95347. }
  95348. if (evt.gamma !== null) {
  95349. this._gamma = +evt.gamma | 0;
  95350. }
  95351. this._dirty = true;
  95352. };
  95353. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  95354. if (this._dirty) {
  95355. this._dirty = false;
  95356. if (this._gamma < 0) {
  95357. this._gamma = 180 + this._gamma;
  95358. }
  95359. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  95360. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  95361. }
  95362. };
  95363. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  95364. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  95365. };
  95366. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  95367. return "ArcRotateCameraVRDeviceOrientationInput";
  95368. };
  95369. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  95370. return "VRDeviceOrientation";
  95371. };
  95372. return ArcRotateCameraVRDeviceOrientationInput;
  95373. }());
  95374. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  95375. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  95376. })(BABYLON || (BABYLON = {}));
  95377. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  95378. var BABYLON;
  95379. (function (BABYLON) {
  95380. var VRCameraMetrics = /** @class */ (function () {
  95381. function VRCameraMetrics() {
  95382. this.compensateDistortion = true;
  95383. }
  95384. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  95385. get: function () {
  95386. return this.hResolution / (2 * this.vResolution);
  95387. },
  95388. enumerable: true,
  95389. configurable: true
  95390. });
  95391. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  95392. get: function () {
  95393. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  95394. },
  95395. enumerable: true,
  95396. configurable: true
  95397. });
  95398. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  95399. get: function () {
  95400. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  95401. var h = (4 * meters) / this.hScreenSize;
  95402. return BABYLON.Matrix.Translation(h, 0, 0);
  95403. },
  95404. enumerable: true,
  95405. configurable: true
  95406. });
  95407. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  95408. get: function () {
  95409. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  95410. var h = (4 * meters) / this.hScreenSize;
  95411. return BABYLON.Matrix.Translation(-h, 0, 0);
  95412. },
  95413. enumerable: true,
  95414. configurable: true
  95415. });
  95416. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  95417. get: function () {
  95418. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  95419. },
  95420. enumerable: true,
  95421. configurable: true
  95422. });
  95423. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  95424. get: function () {
  95425. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  95426. },
  95427. enumerable: true,
  95428. configurable: true
  95429. });
  95430. VRCameraMetrics.GetDefault = function () {
  95431. var result = new VRCameraMetrics();
  95432. result.hResolution = 1280;
  95433. result.vResolution = 800;
  95434. result.hScreenSize = 0.149759993;
  95435. result.vScreenSize = 0.0935999975;
  95436. result.vScreenCenter = 0.0467999987;
  95437. result.eyeToScreenDistance = 0.0410000011;
  95438. result.lensSeparationDistance = 0.0635000020;
  95439. result.interpupillaryDistance = 0.0640000030;
  95440. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  95441. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  95442. result.postProcessScaleFactor = 1.714605507808412;
  95443. result.lensCenterOffset = 0.151976421;
  95444. return result;
  95445. };
  95446. return VRCameraMetrics;
  95447. }());
  95448. BABYLON.VRCameraMetrics = VRCameraMetrics;
  95449. })(BABYLON || (BABYLON = {}));
  95450. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  95451. var BABYLON;
  95452. (function (BABYLON) {
  95453. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  95454. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95455. });
  95456. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  95457. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95458. });
  95459. /**
  95460. * This represents a WebVR camera.
  95461. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  95462. * @example http://doc.babylonjs.com/how_to/webvr_camera
  95463. */
  95464. var WebVRFreeCamera = /** @class */ (function (_super) {
  95465. __extends(WebVRFreeCamera, _super);
  95466. /**
  95467. * Instantiates a WebVRFreeCamera.
  95468. * @param name The name of the WebVRFreeCamera
  95469. * @param position The starting anchor position for the camera
  95470. * @param scene The scene the camera belongs to
  95471. * @param webVROptions a set of customizable options for the webVRCamera
  95472. */
  95473. function WebVRFreeCamera(name, position, scene, webVROptions) {
  95474. if (webVROptions === void 0) { webVROptions = {}; }
  95475. var _this = _super.call(this, name, position, scene) || this;
  95476. _this.webVROptions = webVROptions;
  95477. /**
  95478. * @hidden
  95479. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  95480. */
  95481. _this._vrDevice = null;
  95482. /**
  95483. * The rawPose of the vrDevice.
  95484. */
  95485. _this.rawPose = null;
  95486. _this._specsVersion = "1.1";
  95487. _this._attached = false;
  95488. _this._descendants = [];
  95489. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  95490. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  95491. /** @hidden */
  95492. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  95493. _this._standingMatrix = null;
  95494. /**
  95495. * Represents device position in babylon space.
  95496. */
  95497. _this.devicePosition = BABYLON.Vector3.Zero();
  95498. /**
  95499. * Represents device rotation in babylon space.
  95500. */
  95501. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  95502. /**
  95503. * The scale of the device to be used when translating from device space to babylon space.
  95504. */
  95505. _this.deviceScaleFactor = 1;
  95506. _this._deviceToWorld = BABYLON.Matrix.Identity();
  95507. _this._worldToDevice = BABYLON.Matrix.Identity();
  95508. /**
  95509. * References to the webVR controllers for the vrDevice.
  95510. */
  95511. _this.controllers = [];
  95512. /**
  95513. * Emits an event when a controller is attached.
  95514. */
  95515. _this.onControllersAttachedObservable = new BABYLON.Observable();
  95516. /**
  95517. * Emits an event when a controller's mesh has been loaded;
  95518. */
  95519. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95520. /**
  95521. * Emits an event when the HMD's pose has been updated.
  95522. */
  95523. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  95524. _this._poseSet = false;
  95525. /**
  95526. * If the rig cameras be used as parent instead of this camera.
  95527. */
  95528. _this.rigParenting = true;
  95529. _this._defaultHeight = undefined;
  95530. _this._htmlElementAttached = null;
  95531. _this._detachIfAttached = function () {
  95532. var vrDisplay = _this.getEngine().getVRDevice();
  95533. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  95534. _this.detachControl(_this._htmlElementAttached);
  95535. }
  95536. };
  95537. _this._workingVector = BABYLON.Vector3.Zero();
  95538. _this._oneVector = BABYLON.Vector3.One();
  95539. _this._workingMatrix = BABYLON.Matrix.Identity();
  95540. _this._tmpMatrix = new BABYLON.Matrix();
  95541. _this._cache.position = BABYLON.Vector3.Zero();
  95542. if (webVROptions.defaultHeight) {
  95543. _this._defaultHeight = webVROptions.defaultHeight;
  95544. _this.position.y = _this._defaultHeight;
  95545. }
  95546. _this.minZ = 0.1;
  95547. //legacy support - the compensation boolean was removed.
  95548. if (arguments.length === 5) {
  95549. _this.webVROptions = arguments[4];
  95550. }
  95551. // default webVR options
  95552. if (_this.webVROptions.trackPosition == undefined) {
  95553. _this.webVROptions.trackPosition = true;
  95554. }
  95555. if (_this.webVROptions.controllerMeshes == undefined) {
  95556. _this.webVROptions.controllerMeshes = true;
  95557. }
  95558. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  95559. _this.webVROptions.defaultLightingOnControllers = true;
  95560. }
  95561. _this.rotationQuaternion = new BABYLON.Quaternion();
  95562. if (_this.webVROptions && _this.webVROptions.positionScale) {
  95563. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  95564. }
  95565. //enable VR
  95566. var engine = _this.getEngine();
  95567. _this._onVREnabled = function (success) { if (success) {
  95568. _this.initControllers();
  95569. } };
  95570. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  95571. engine.initWebVR().add(function (event) {
  95572. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  95573. return;
  95574. }
  95575. _this._vrDevice = event.vrDisplay;
  95576. //reset the rig parameters.
  95577. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  95578. if (_this._attached) {
  95579. _this.getEngine().enableVR();
  95580. }
  95581. });
  95582. if (typeof (VRFrameData) !== "undefined")
  95583. _this._frameData = new VRFrameData();
  95584. /**
  95585. * The idea behind the following lines:
  95586. * objects that have the camera as parent should actually have the rig cameras as a parent.
  95587. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  95588. * the second will not show it correctly.
  95589. *
  95590. * To solve this - each object that has the camera as parent will be added to a protected array.
  95591. * When the rig camera renders, it will take this array and set all of those to be its children.
  95592. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  95593. * Amazing!
  95594. */
  95595. scene.onBeforeCameraRenderObservable.add(function (camera) {
  95596. if (camera.parent === _this && _this.rigParenting) {
  95597. _this._descendants = _this.getDescendants(true, function (n) {
  95598. // don't take the cameras or the controllers!
  95599. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  95600. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  95601. return !isController && !isRigCamera;
  95602. });
  95603. _this._descendants.forEach(function (node) {
  95604. node.parent = camera;
  95605. });
  95606. }
  95607. });
  95608. scene.onAfterCameraRenderObservable.add(function (camera) {
  95609. if (camera.parent === _this && _this.rigParenting) {
  95610. _this._descendants.forEach(function (node) {
  95611. node.parent = _this;
  95612. });
  95613. }
  95614. });
  95615. return _this;
  95616. }
  95617. /**
  95618. * Gets the device distance from the ground in meters.
  95619. * @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.
  95620. */
  95621. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  95622. if (this._standingMatrix) {
  95623. // Add standing matrix offset to get real offset from ground in room
  95624. this._standingMatrix.getTranslationToRef(this._workingVector);
  95625. return this._deviceRoomPosition.y + this._workingVector.y;
  95626. }
  95627. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  95628. return this._defaultHeight || 0;
  95629. };
  95630. /**
  95631. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95632. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  95633. */
  95634. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  95635. var _this = this;
  95636. if (callback === void 0) { callback = function (bool) { }; }
  95637. // Use standing matrix if available
  95638. this.getEngine().initWebVRAsync().then(function (result) {
  95639. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  95640. callback(false);
  95641. }
  95642. else {
  95643. _this._standingMatrix = new BABYLON.Matrix();
  95644. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  95645. if (!_this.getScene().useRightHandedSystem) {
  95646. [2, 6, 8, 9, 14].forEach(function (num) {
  95647. if (_this._standingMatrix) {
  95648. _this._standingMatrix.m[num] *= -1;
  95649. }
  95650. });
  95651. }
  95652. callback(true);
  95653. }
  95654. });
  95655. };
  95656. /**
  95657. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95658. * @returns A promise with a boolean set to if the standing matrix is supported.
  95659. */
  95660. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  95661. var _this = this;
  95662. return new Promise(function (res, rej) {
  95663. _this.useStandingMatrix(function (supported) {
  95664. res(supported);
  95665. });
  95666. });
  95667. };
  95668. /**
  95669. * Disposes the camera
  95670. */
  95671. WebVRFreeCamera.prototype.dispose = function () {
  95672. this._detachIfAttached();
  95673. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  95674. _super.prototype.dispose.call(this);
  95675. };
  95676. /**
  95677. * Gets a vrController by name.
  95678. * @param name The name of the controller to retreive
  95679. * @returns the controller matching the name specified or null if not found
  95680. */
  95681. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  95682. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  95683. var gp = _a[_i];
  95684. if (gp.hand === name) {
  95685. return gp;
  95686. }
  95687. }
  95688. return null;
  95689. };
  95690. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  95691. /**
  95692. * The controller corrisponding to the users left hand.
  95693. */
  95694. get: function () {
  95695. if (!this._leftController) {
  95696. this._leftController = this.getControllerByName("left");
  95697. }
  95698. return this._leftController;
  95699. },
  95700. enumerable: true,
  95701. configurable: true
  95702. });
  95703. ;
  95704. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  95705. /**
  95706. * The controller corrisponding to the users right hand.
  95707. */
  95708. get: function () {
  95709. if (!this._rightController) {
  95710. this._rightController = this.getControllerByName("right");
  95711. }
  95712. return this._rightController;
  95713. },
  95714. enumerable: true,
  95715. configurable: true
  95716. });
  95717. ;
  95718. /**
  95719. * Casts a ray forward from the vrCamera's gaze.
  95720. * @param length Length of the ray (default: 100)
  95721. * @returns the ray corrisponding to the gaze
  95722. */
  95723. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95724. if (length === void 0) { length = 100; }
  95725. if (this.leftCamera) {
  95726. // Use left eye to avoid computation to compute center on every call
  95727. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95728. }
  95729. else {
  95730. return _super.prototype.getForwardRay.call(this, length);
  95731. }
  95732. };
  95733. /**
  95734. * @hidden
  95735. * Updates the camera based on device's frame data
  95736. */
  95737. WebVRFreeCamera.prototype._checkInputs = function () {
  95738. if (this._vrDevice && this._vrDevice.isPresenting) {
  95739. this._vrDevice.getFrameData(this._frameData);
  95740. this.updateFromDevice(this._frameData.pose);
  95741. }
  95742. _super.prototype._checkInputs.call(this);
  95743. };
  95744. /**
  95745. * Updates the poseControlled values based on the input device pose.
  95746. * @param poseData Pose coming from the device
  95747. */
  95748. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95749. if (poseData && poseData.orientation) {
  95750. this.rawPose = poseData;
  95751. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95752. if (this.getScene().useRightHandedSystem) {
  95753. this._deviceRoomRotationQuaternion.z *= -1;
  95754. this._deviceRoomRotationQuaternion.w *= -1;
  95755. }
  95756. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95757. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95758. if (this.getScene().useRightHandedSystem) {
  95759. this._deviceRoomPosition.z *= -1;
  95760. }
  95761. }
  95762. this._poseSet = true;
  95763. }
  95764. };
  95765. /**
  95766. * WebVR's attach control will start broadcasting frames to the device.
  95767. * Note that in certain browsers (chrome for example) this function must be called
  95768. * within a user-interaction callback. Example:
  95769. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95770. *
  95771. * @param element html element to attach the vrDevice to
  95772. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95773. */
  95774. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95775. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95776. this._attached = true;
  95777. this._htmlElementAttached = element;
  95778. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95779. if (this._vrDevice) {
  95780. this.getEngine().enableVR();
  95781. }
  95782. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95783. };
  95784. /**
  95785. * Detaches the camera from the html element and disables VR
  95786. *
  95787. * @param element html element to detach from
  95788. */
  95789. WebVRFreeCamera.prototype.detachControl = function (element) {
  95790. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  95791. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  95792. _super.prototype.detachControl.call(this, element);
  95793. this._attached = false;
  95794. this.getEngine().disableVR();
  95795. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95796. };
  95797. /**
  95798. * @returns the name of this class
  95799. */
  95800. WebVRFreeCamera.prototype.getClassName = function () {
  95801. return "WebVRFreeCamera";
  95802. };
  95803. /**
  95804. * Calls resetPose on the vrDisplay
  95805. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  95806. */
  95807. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  95808. //uses the vrDisplay's "resetPose()".
  95809. //pitch and roll won't be affected.
  95810. this._vrDevice.resetPose();
  95811. };
  95812. /**
  95813. * @hidden
  95814. * Updates the rig cameras (left and right eye)
  95815. */
  95816. WebVRFreeCamera.prototype._updateRigCameras = function () {
  95817. var camLeft = this._rigCameras[0];
  95818. var camRight = this._rigCameras[1];
  95819. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95820. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95821. camLeft.position.copyFrom(this._deviceRoomPosition);
  95822. camRight.position.copyFrom(this._deviceRoomPosition);
  95823. };
  95824. // Remove translation from 6dof headset if trackposition is set to false
  95825. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  95826. if (isViewMatrix === void 0) { isViewMatrix = false; }
  95827. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  95828. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  95829. if (!isViewMatrix) {
  95830. this._tmpMatrix.invert();
  95831. }
  95832. this._tmpMatrix.multiplyToRef(matrix, matrix);
  95833. }
  95834. };
  95835. /**
  95836. * @hidden
  95837. * Updates the cached values of the camera
  95838. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  95839. */
  95840. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  95841. var _this = this;
  95842. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  95843. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  95844. if (!this.updateCacheCalled) {
  95845. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  95846. this.updateCacheCalled = true;
  95847. this.update();
  95848. }
  95849. // Set working vector to the device position in room space rotated by the new rotation
  95850. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  95851. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  95852. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  95853. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  95854. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  95855. // Add translation from anchor position
  95856. this._deviceToWorld.getTranslationToRef(this._workingVector);
  95857. this._workingVector.addInPlace(this.position);
  95858. this._workingVector.subtractInPlace(this._cache.position);
  95859. this._deviceToWorld.setTranslation(this._workingVector);
  95860. // Set an inverted matrix to be used when updating the camera
  95861. this._deviceToWorld.invertToRef(this._worldToDevice);
  95862. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  95863. this.controllers.forEach(function (controller) {
  95864. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  95865. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  95866. controller.update();
  95867. });
  95868. }
  95869. if (!ignoreParentClass) {
  95870. _super.prototype._updateCache.call(this);
  95871. }
  95872. this.updateCacheCalled = false;
  95873. };
  95874. /**
  95875. * Updates the current device position and rotation in the babylon world
  95876. */
  95877. WebVRFreeCamera.prototype.update = function () {
  95878. // Get current device position in babylon world
  95879. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  95880. // Get current device rotation in babylon world
  95881. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  95882. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  95883. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  95884. if (this._poseSet) {
  95885. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  95886. }
  95887. _super.prototype.update.call(this);
  95888. };
  95889. /**
  95890. * @hidden
  95891. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  95892. * @returns an identity matrix
  95893. */
  95894. WebVRFreeCamera.prototype._getViewMatrix = function () {
  95895. return BABYLON.Matrix.Identity();
  95896. };
  95897. /**
  95898. * This function is called by the two RIG cameras.
  95899. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  95900. */
  95901. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  95902. var _this = this;
  95903. // Update the parent camera prior to using a child camera to avoid desynchronization
  95904. var parentCamera = this._cameraRigParams["parentCamera"];
  95905. parentCamera._updateCache();
  95906. //WebVR 1.1
  95907. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  95908. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  95909. if (!this.getScene().useRightHandedSystem) {
  95910. [2, 6, 8, 9, 14].forEach(function (num) {
  95911. _this._webvrViewMatrix.m[num] *= -1;
  95912. });
  95913. }
  95914. // update the camera rotation matrix
  95915. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  95916. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  95917. // Computing target and final matrix
  95918. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  95919. // should the view matrix be updated with scale and position offset?
  95920. if (parentCamera.deviceScaleFactor !== 1) {
  95921. this._webvrViewMatrix.invert();
  95922. // scale the position, if set
  95923. if (parentCamera.deviceScaleFactor) {
  95924. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  95925. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  95926. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  95927. }
  95928. this._webvrViewMatrix.invert();
  95929. }
  95930. // Remove translation from 6dof headset if trackposition is set to false
  95931. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  95932. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95933. // Compute global position
  95934. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  95935. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  95936. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  95937. this._workingMatrix.getTranslationToRef(this._globalPosition);
  95938. this._markSyncedWithParent();
  95939. return this._webvrViewMatrix;
  95940. };
  95941. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  95942. var _this = this;
  95943. var parentCamera = this.parent;
  95944. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  95945. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  95946. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  95947. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  95948. //babylon compatible matrix
  95949. if (!this.getScene().useRightHandedSystem) {
  95950. [8, 9, 10, 11].forEach(function (num) {
  95951. _this._projectionMatrix.m[num] *= -1;
  95952. });
  95953. }
  95954. return this._projectionMatrix;
  95955. };
  95956. /**
  95957. * Initializes the controllers and their meshes
  95958. */
  95959. WebVRFreeCamera.prototype.initControllers = function () {
  95960. var _this = this;
  95961. this.controllers = [];
  95962. var manager = this.getScene().gamepadManager;
  95963. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  95964. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95965. var webVrController = gamepad;
  95966. if (webVrController.defaultModel) {
  95967. webVrController.defaultModel.setEnabled(false);
  95968. }
  95969. if (webVrController.hand === "right") {
  95970. _this._rightController = null;
  95971. }
  95972. if (webVrController.hand === "left") {
  95973. _this._leftController = null;
  95974. }
  95975. var controllerIndex = _this.controllers.indexOf(webVrController);
  95976. if (controllerIndex !== -1) {
  95977. _this.controllers.splice(controllerIndex, 1);
  95978. }
  95979. }
  95980. });
  95981. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  95982. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95983. var webVrController_1 = gamepad;
  95984. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  95985. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  95986. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  95987. if (_this.webVROptions.controllerMeshes) {
  95988. if (webVrController_1.defaultModel) {
  95989. webVrController_1.defaultModel.setEnabled(true);
  95990. }
  95991. else {
  95992. // Load the meshes
  95993. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  95994. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  95995. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  95996. if (_this.webVROptions.defaultLightingOnControllers) {
  95997. if (!_this._lightOnControllers) {
  95998. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  95999. }
  96000. var activateLightOnSubMeshes_1 = function (mesh, light) {
  96001. var children = mesh.getChildren();
  96002. if (children.length !== 0) {
  96003. children.forEach(function (mesh) {
  96004. light.includedOnlyMeshes.push(mesh);
  96005. activateLightOnSubMeshes_1(mesh, light);
  96006. });
  96007. }
  96008. };
  96009. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  96010. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  96011. }
  96012. });
  96013. }
  96014. }
  96015. webVrController_1.attachToPoseControlledCamera(_this);
  96016. // since this is async - sanity check. Is the controller already stored?
  96017. if (_this.controllers.indexOf(webVrController_1) === -1) {
  96018. //add to the controllers array
  96019. _this.controllers.push(webVrController_1);
  96020. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  96021. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  96022. // So we're overriding setting left & right manually to be sure
  96023. var firstViveWandDetected = false;
  96024. for (var i = 0; i < _this.controllers.length; i++) {
  96025. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96026. if (!firstViveWandDetected) {
  96027. firstViveWandDetected = true;
  96028. _this.controllers[i].hand = "left";
  96029. }
  96030. else {
  96031. _this.controllers[i].hand = "right";
  96032. }
  96033. }
  96034. }
  96035. //did we find enough controllers? Great! let the developer know.
  96036. if (_this.controllers.length >= 2) {
  96037. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  96038. }
  96039. }
  96040. }
  96041. });
  96042. };
  96043. return WebVRFreeCamera;
  96044. }(BABYLON.FreeCamera));
  96045. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  96046. })(BABYLON || (BABYLON = {}));
  96047. //# sourceMappingURL=babylon.webVRCamera.js.map
  96048. var BABYLON;
  96049. (function (BABYLON) {
  96050. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  96051. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  96052. });
  96053. // We're mainly based on the logic defined into the FreeCamera code
  96054. /**
  96055. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  96056. * being tilted forward or back and left or right.
  96057. */
  96058. var DeviceOrientationCamera = /** @class */ (function (_super) {
  96059. __extends(DeviceOrientationCamera, _super);
  96060. /**
  96061. * Creates a new device orientation camera
  96062. * @param name The name of the camera
  96063. * @param position The start position camera
  96064. * @param scene The scene the camera belongs to
  96065. */
  96066. function DeviceOrientationCamera(name, position, scene) {
  96067. var _this = _super.call(this, name, position, scene) || this;
  96068. _this._quaternionCache = new BABYLON.Quaternion();
  96069. _this.inputs.addDeviceOrientation();
  96070. return _this;
  96071. }
  96072. /**
  96073. * Gets the current instance class name ("DeviceOrientationCamera").
  96074. * This helps avoiding instanceof at run time.
  96075. * @returns the class name
  96076. */
  96077. DeviceOrientationCamera.prototype.getClassName = function () {
  96078. return "DeviceOrientationCamera";
  96079. };
  96080. /**
  96081. * @hidden
  96082. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  96083. */
  96084. DeviceOrientationCamera.prototype._checkInputs = function () {
  96085. _super.prototype._checkInputs.call(this);
  96086. this._quaternionCache.copyFrom(this.rotationQuaternion);
  96087. if (this._initialQuaternion) {
  96088. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96089. }
  96090. };
  96091. /**
  96092. * Reset the camera to its default orientation on the specified axis only.
  96093. * @param axis The axis to reset
  96094. */
  96095. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  96096. var _this = this;
  96097. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  96098. //can only work if this camera has a rotation quaternion already.
  96099. if (!this.rotationQuaternion)
  96100. return;
  96101. if (!this._initialQuaternion) {
  96102. this._initialQuaternion = new BABYLON.Quaternion();
  96103. }
  96104. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  96105. ['x', 'y', 'z'].forEach(function (axisName) {
  96106. if (!axis[axisName]) {
  96107. _this._initialQuaternion[axisName] = 0;
  96108. }
  96109. else {
  96110. _this._initialQuaternion[axisName] *= -1;
  96111. }
  96112. });
  96113. this._initialQuaternion.normalize();
  96114. //force rotation update
  96115. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96116. };
  96117. return DeviceOrientationCamera;
  96118. }(BABYLON.FreeCamera));
  96119. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  96120. })(BABYLON || (BABYLON = {}));
  96121. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  96122. var BABYLON;
  96123. (function (BABYLON) {
  96124. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96125. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96126. });
  96127. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  96128. __extends(VRDeviceOrientationFreeCamera, _super);
  96129. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  96130. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96131. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96132. var _this = _super.call(this, name, position, scene) || this;
  96133. vrCameraMetrics.compensateDistortion = compensateDistortion;
  96134. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  96135. return _this;
  96136. }
  96137. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  96138. return "VRDeviceOrientationFreeCamera";
  96139. };
  96140. return VRDeviceOrientationFreeCamera;
  96141. }(BABYLON.DeviceOrientationCamera));
  96142. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  96143. })(BABYLON || (BABYLON = {}));
  96144. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  96145. var BABYLON;
  96146. (function (BABYLON) {
  96147. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96148. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  96149. });
  96150. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  96151. __extends(VRDeviceOrientationArcRotateCamera, _super);
  96152. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  96153. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96154. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96155. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96156. vrCameraMetrics.compensateDistortion = compensateDistortion;
  96157. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  96158. _this.inputs.addVRDeviceOrientation();
  96159. return _this;
  96160. }
  96161. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  96162. return "VRDeviceOrientationArcRotateCamera";
  96163. };
  96164. return VRDeviceOrientationArcRotateCamera;
  96165. }(BABYLON.ArcRotateCamera));
  96166. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  96167. })(BABYLON || (BABYLON = {}));
  96168. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  96169. var BABYLON;
  96170. (function (BABYLON) {
  96171. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  96172. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  96173. });
  96174. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  96175. __extends(VRDeviceOrientationGamepadCamera, _super);
  96176. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  96177. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96178. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96179. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  96180. _this.inputs.addGamepad();
  96181. return _this;
  96182. }
  96183. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  96184. return "VRDeviceOrientationGamepadCamera";
  96185. };
  96186. return VRDeviceOrientationGamepadCamera;
  96187. }(BABYLON.VRDeviceOrientationFreeCamera));
  96188. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  96189. })(BABYLON || (BABYLON = {}));
  96190. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  96191. var BABYLON;
  96192. (function (BABYLON) {
  96193. var VRExperienceHelperGazer = /** @class */ (function () {
  96194. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  96195. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  96196. this.scene = scene;
  96197. /** @hidden */
  96198. this._pointerDownOnMeshAsked = false;
  96199. /** @hidden */
  96200. this._isActionableMesh = false;
  96201. /** @hidden */
  96202. this._teleportationRequestInitiated = false;
  96203. /** @hidden */
  96204. this._teleportationBackRequestInitiated = false;
  96205. /** @hidden */
  96206. this._rotationRightAsked = false;
  96207. /** @hidden */
  96208. this._rotationLeftAsked = false;
  96209. /** @hidden */
  96210. this._dpadPressed = true;
  96211. /** @hidden */
  96212. this._activePointer = false;
  96213. this._id = VRExperienceHelperGazer._idCounter++;
  96214. // Gaze tracker
  96215. if (!gazeTrackerToClone) {
  96216. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  96217. this._gazeTracker.bakeCurrentTransformIntoVertices();
  96218. this._gazeTracker.isPickable = false;
  96219. this._gazeTracker.isVisible = false;
  96220. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  96221. targetMat.specularColor = BABYLON.Color3.Black();
  96222. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  96223. targetMat.backFaceCulling = false;
  96224. this._gazeTracker.material = targetMat;
  96225. }
  96226. else {
  96227. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  96228. }
  96229. }
  96230. /** @hidden */
  96231. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  96232. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  96233. };
  96234. /** @hidden */
  96235. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  96236. this._pointerDownOnMeshAsked = true;
  96237. if (this._currentHit) {
  96238. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  96239. }
  96240. };
  96241. /** @hidden */
  96242. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  96243. if (this._currentHit) {
  96244. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  96245. }
  96246. this._pointerDownOnMeshAsked = false;
  96247. };
  96248. /** @hidden */
  96249. VRExperienceHelperGazer.prototype._activatePointer = function () {
  96250. this._activePointer = true;
  96251. };
  96252. /** @hidden */
  96253. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  96254. this._activePointer = false;
  96255. };
  96256. /** @hidden */
  96257. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  96258. if (distance === void 0) { distance = 100; }
  96259. };
  96260. VRExperienceHelperGazer.prototype.dispose = function () {
  96261. this._interactionsEnabled = false;
  96262. this._teleportationEnabled = false;
  96263. if (this._gazeTracker) {
  96264. this._gazeTracker.dispose();
  96265. }
  96266. };
  96267. VRExperienceHelperGazer._idCounter = 0;
  96268. return VRExperienceHelperGazer;
  96269. }());
  96270. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  96271. __extends(VRExperienceHelperControllerGazer, _super);
  96272. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  96273. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  96274. _this.webVRController = webVRController;
  96275. // Laser pointer
  96276. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  96277. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  96278. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  96279. laserPointerMaterial.alpha = 0.6;
  96280. _this._laserPointer.material = laserPointerMaterial;
  96281. _this._laserPointer.rotation.x = Math.PI / 2;
  96282. _this._laserPointer.position.z = -0.5;
  96283. _this._laserPointer.isVisible = false;
  96284. _this._laserPointer.isPickable = false;
  96285. if (!webVRController.mesh) {
  96286. // Create an empty mesh that is used prior to loading the high quality model
  96287. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  96288. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  96289. preloadPointerPose.rotation.x = -0.7;
  96290. preloadMesh.addChild(preloadPointerPose);
  96291. webVRController.attachToMesh(preloadMesh);
  96292. }
  96293. _this._setLaserPointerParent(webVRController.mesh);
  96294. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  96295. _this._setLaserPointerParent(mesh);
  96296. });
  96297. return _this;
  96298. }
  96299. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  96300. return this.webVRController.getForwardRay(length);
  96301. };
  96302. /** @hidden */
  96303. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  96304. _super.prototype._activatePointer.call(this);
  96305. this._laserPointer.isVisible = true;
  96306. };
  96307. /** @hidden */
  96308. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  96309. _super.prototype._deactivatePointer.call(this);
  96310. this._laserPointer.isVisible = false;
  96311. };
  96312. /** @hidden */
  96313. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  96314. this._laserPointer.material.emissiveColor = color;
  96315. };
  96316. /** @hidden */
  96317. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  96318. var makeNotPick = function (root) {
  96319. root.isPickable = false;
  96320. root.getChildMeshes().forEach(function (c) {
  96321. makeNotPick(c);
  96322. });
  96323. };
  96324. makeNotPick(mesh);
  96325. var childMeshes = mesh.getChildMeshes();
  96326. this.webVRController._pointingPoseNode = null;
  96327. for (var i = 0; i < childMeshes.length; i++) {
  96328. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  96329. mesh = childMeshes[i];
  96330. this.webVRController._pointingPoseNode = mesh;
  96331. break;
  96332. }
  96333. }
  96334. this._laserPointer.parent = mesh;
  96335. };
  96336. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  96337. if (distance === void 0) { distance = 100; }
  96338. this._laserPointer.scaling.y = distance;
  96339. this._laserPointer.position.z = -distance / 2;
  96340. };
  96341. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  96342. _super.prototype.dispose.call(this);
  96343. this._laserPointer.dispose();
  96344. if (this._meshAttachedObserver) {
  96345. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  96346. }
  96347. };
  96348. return VRExperienceHelperControllerGazer;
  96349. }(VRExperienceHelperGazer));
  96350. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  96351. __extends(VRExperienceHelperCameraGazer, _super);
  96352. function VRExperienceHelperCameraGazer(getCamera, scene) {
  96353. var _this = _super.call(this, scene) || this;
  96354. _this.getCamera = getCamera;
  96355. return _this;
  96356. }
  96357. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  96358. var camera = this.getCamera();
  96359. if (camera) {
  96360. return camera.getForwardRay(length);
  96361. }
  96362. else {
  96363. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  96364. }
  96365. };
  96366. return VRExperienceHelperCameraGazer;
  96367. }(VRExperienceHelperGazer));
  96368. /**
  96369. * Helps to quickly add VR support to an existing scene.
  96370. * See http://doc.babylonjs.com/how_to/webvr_helper
  96371. */
  96372. var VRExperienceHelper = /** @class */ (function () {
  96373. /**
  96374. * Instantiates a VRExperienceHelper.
  96375. * Helps to quickly add VR support to an existing scene.
  96376. * @param scene The scene the VRExperienceHelper belongs to.
  96377. * @param webVROptions Options to modify the vr experience helper's behavior.
  96378. */
  96379. function VRExperienceHelper(scene,
  96380. /** Options to modify the vr experience helper's behavior. */
  96381. webVROptions) {
  96382. if (webVROptions === void 0) { webVROptions = {}; }
  96383. var _this = this;
  96384. this.webVROptions = webVROptions;
  96385. // Can the system support WebVR, even if a headset isn't plugged in?
  96386. this._webVRsupported = false;
  96387. // If WebVR is supported, is a headset plugged in and are we ready to present?
  96388. this._webVRready = false;
  96389. // Are we waiting for the requestPresent callback to complete?
  96390. this._webVRrequesting = false;
  96391. // Are we presenting to the headset right now? (this is the vrDevice state)
  96392. this._webVRpresenting = false;
  96393. // Are we presenting in the fullscreen fallback?
  96394. this._fullscreenVRpresenting = false;
  96395. /**
  96396. * Observable raised when entering VR.
  96397. */
  96398. this.onEnteringVRObservable = new BABYLON.Observable();
  96399. /**
  96400. * Observable raised when exiting VR.
  96401. */
  96402. this.onExitingVRObservable = new BABYLON.Observable();
  96403. /**
  96404. * Observable raised when controller mesh is loaded.
  96405. */
  96406. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96407. this._useCustomVRButton = false;
  96408. this._teleportationRequested = false;
  96409. this._teleportActive = false;
  96410. this._floorMeshesCollection = [];
  96411. this._rotationAllowed = true;
  96412. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  96413. this._isDefaultTeleportationTarget = true;
  96414. this._teleportationFillColor = "#444444";
  96415. this._teleportationBorderColor = "#FFFFFF";
  96416. this._rotationAngle = 0;
  96417. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  96418. this._padSensibilityUp = 0.65;
  96419. this._padSensibilityDown = 0.35;
  96420. this._leftController = null;
  96421. this._rightController = null;
  96422. /**
  96423. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  96424. */
  96425. this.onNewMeshSelected = new BABYLON.Observable();
  96426. /**
  96427. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  96428. */
  96429. this.onNewMeshPicked = new BABYLON.Observable();
  96430. /**
  96431. * Observable raised before camera teleportation
  96432. */
  96433. this.onBeforeCameraTeleport = new BABYLON.Observable();
  96434. /**
  96435. * Observable raised after camera teleportation
  96436. */
  96437. this.onAfterCameraTeleport = new BABYLON.Observable();
  96438. /**
  96439. * Observable raised when current selected mesh gets unselected
  96440. */
  96441. this.onSelectedMeshUnselected = new BABYLON.Observable();
  96442. /**
  96443. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  96444. */
  96445. this.teleportationEnabled = true;
  96446. this._teleportationInitialized = false;
  96447. this._interactionsEnabled = false;
  96448. this._interactionsRequested = false;
  96449. this._displayGaze = true;
  96450. this._displayLaserPointer = true;
  96451. /**
  96452. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  96453. */
  96454. this.updateGazeTrackerScale = true;
  96455. this._onResize = function () {
  96456. _this.moveButtonToBottomRight();
  96457. if (_this._fullscreenVRpresenting && _this._webVRready) {
  96458. _this.exitVR();
  96459. }
  96460. };
  96461. this._onFullscreenChange = function () {
  96462. if (document.fullscreen !== undefined) {
  96463. _this._fullscreenVRpresenting = document.fullscreen;
  96464. }
  96465. else if (document.mozFullScreen !== undefined) {
  96466. _this._fullscreenVRpresenting = document.mozFullScreen;
  96467. }
  96468. else if (document.webkitIsFullScreen !== undefined) {
  96469. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  96470. }
  96471. else if (document.msIsFullScreen !== undefined) {
  96472. _this._fullscreenVRpresenting = document.msIsFullScreen;
  96473. }
  96474. else if (document.msFullscreenElement !== undefined) {
  96475. _this._fullscreenVRpresenting = document.msFullscreenElement;
  96476. }
  96477. if (!_this._fullscreenVRpresenting && _this._canvas) {
  96478. _this.exitVR();
  96479. if (!_this._useCustomVRButton) {
  96480. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  96481. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  96482. }
  96483. }
  96484. };
  96485. this.beforeRender = function () {
  96486. if (_this._leftController && _this._leftController._activePointer) {
  96487. _this._castRayAndSelectObject(_this._leftController);
  96488. }
  96489. if (_this._rightController && _this._rightController._activePointer) {
  96490. _this._castRayAndSelectObject(_this._rightController);
  96491. }
  96492. if (_this._noControllerIsActive) {
  96493. _this._castRayAndSelectObject(_this._cameraGazer);
  96494. }
  96495. else {
  96496. _this._cameraGazer._gazeTracker.isVisible = false;
  96497. }
  96498. };
  96499. this._onNewGamepadConnected = function (gamepad) {
  96500. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  96501. if (gamepad.leftStick) {
  96502. gamepad.onleftstickchanged(function (stickValues) {
  96503. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  96504. // Listening to classic/xbox gamepad only if no VR controller is active
  96505. if ((!_this._leftController && !_this._rightController) ||
  96506. ((_this._leftController && !_this._leftController._activePointer) &&
  96507. (_this._rightController && !_this._rightController._activePointer))) {
  96508. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  96509. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  96510. }
  96511. }
  96512. });
  96513. }
  96514. if (gamepad.rightStick) {
  96515. gamepad.onrightstickchanged(function (stickValues) {
  96516. if (_this._teleportationInitialized) {
  96517. _this._checkRotate(stickValues, _this._cameraGazer);
  96518. }
  96519. });
  96520. }
  96521. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  96522. gamepad.onbuttondown(function (buttonPressed) {
  96523. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96524. _this._cameraGazer._selectionPointerDown();
  96525. }
  96526. });
  96527. gamepad.onbuttonup(function (buttonPressed) {
  96528. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96529. _this._cameraGazer._selectionPointerUp();
  96530. }
  96531. });
  96532. }
  96533. }
  96534. else {
  96535. var webVRController = gamepad;
  96536. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  96537. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  96538. _this._rightController = controller;
  96539. }
  96540. else {
  96541. _this._leftController = controller;
  96542. }
  96543. _this._tryEnableInteractionOnController(controller);
  96544. }
  96545. };
  96546. // 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
  96547. this._tryEnableInteractionOnController = function (controller) {
  96548. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  96549. _this._enableInteractionOnController(controller);
  96550. }
  96551. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  96552. _this._enableTeleportationOnController(controller);
  96553. }
  96554. };
  96555. this._onNewGamepadDisconnected = function (gamepad) {
  96556. if (gamepad instanceof BABYLON.WebVRController) {
  96557. if (gamepad.hand === "left" && _this._leftController != null) {
  96558. _this._leftController.dispose();
  96559. _this._leftController = null;
  96560. }
  96561. if (gamepad.hand === "right" && _this._rightController != null) {
  96562. _this._rightController.dispose();
  96563. _this._rightController = null;
  96564. }
  96565. }
  96566. };
  96567. this._workingVector = BABYLON.Vector3.Zero();
  96568. this._workingQuaternion = BABYLON.Quaternion.Identity();
  96569. this._workingMatrix = BABYLON.Matrix.Identity();
  96570. this._scene = scene;
  96571. this._canvas = scene.getEngine().getRenderingCanvas();
  96572. // Parse options
  96573. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  96574. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  96575. }
  96576. if (webVROptions.createDeviceOrientationCamera === undefined) {
  96577. webVROptions.createDeviceOrientationCamera = true;
  96578. }
  96579. if (webVROptions.laserToggle === undefined) {
  96580. webVROptions.laserToggle = true;
  96581. }
  96582. if (webVROptions.defaultHeight === undefined) {
  96583. webVROptions.defaultHeight = 1.7;
  96584. }
  96585. if (webVROptions.useCustomVRButton) {
  96586. this._useCustomVRButton = true;
  96587. if (webVROptions.customVRButton) {
  96588. this._btnVR = webVROptions.customVRButton;
  96589. }
  96590. }
  96591. if (webVROptions.rayLength) {
  96592. this._rayLength = webVROptions.rayLength;
  96593. }
  96594. this._defaultHeight = webVROptions.defaultHeight;
  96595. if (webVROptions.positionScale) {
  96596. this._rayLength *= webVROptions.positionScale;
  96597. this._defaultHeight *= webVROptions.positionScale;
  96598. }
  96599. this._hasEnteredVR = false;
  96600. // Set position
  96601. if (this._scene.activeCamera) {
  96602. this._position = this._scene.activeCamera.position.clone();
  96603. }
  96604. else {
  96605. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  96606. }
  96607. // Set non-vr camera
  96608. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  96609. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  96610. // Copy data from existing camera
  96611. if (this._scene.activeCamera) {
  96612. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96613. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  96614. // Set rotation from previous camera
  96615. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  96616. var targetCamera = this._scene.activeCamera;
  96617. if (targetCamera.rotationQuaternion) {
  96618. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  96619. }
  96620. else {
  96621. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  96622. }
  96623. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  96624. }
  96625. }
  96626. this._scene.activeCamera = this._deviceOrientationCamera;
  96627. if (this._canvas) {
  96628. this._scene.activeCamera.attachControl(this._canvas);
  96629. }
  96630. }
  96631. else {
  96632. this._existingCamera = this._scene.activeCamera;
  96633. }
  96634. // Create VR cameras
  96635. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96636. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  96637. }
  96638. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  96639. this._webVRCamera.useStandingMatrix();
  96640. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  96641. // Create default button
  96642. if (!this._useCustomVRButton) {
  96643. this._btnVR = document.createElement("BUTTON");
  96644. this._btnVR.className = "babylonVRicon";
  96645. this._btnVR.id = "babylonVRiconbtn";
  96646. this._btnVR.title = "Click to switch to VR";
  96647. 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) }";
  96648. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  96649. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  96650. // css += ".babylonVRicon.vrdisplaysupported { }";
  96651. // css += ".babylonVRicon.vrdisplayready { }";
  96652. // css += ".babylonVRicon.vrdisplayrequesting { }";
  96653. var style = document.createElement('style');
  96654. style.appendChild(document.createTextNode(css));
  96655. document.getElementsByTagName('head')[0].appendChild(style);
  96656. this.moveButtonToBottomRight();
  96657. }
  96658. // VR button click event
  96659. if (this._btnVR) {
  96660. this._btnVR.addEventListener("click", function () {
  96661. if (!_this.isInVRMode) {
  96662. _this.enterVR();
  96663. }
  96664. else {
  96665. _this.exitVR();
  96666. }
  96667. });
  96668. }
  96669. // Window events
  96670. window.addEventListener("resize", this._onResize);
  96671. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  96672. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  96673. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  96674. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  96675. document.onmsfullscreenchange = this._onFullscreenChange;
  96676. // Display vr button when headset is connected
  96677. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96678. this.displayVRButton();
  96679. }
  96680. else {
  96681. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  96682. if (e.vrDisplay) {
  96683. _this.displayVRButton();
  96684. }
  96685. });
  96686. }
  96687. // Exiting VR mode using 'ESC' key on desktop
  96688. this._onKeyDown = function (event) {
  96689. if (event.keyCode === 27 && _this.isInVRMode) {
  96690. _this.exitVR();
  96691. }
  96692. };
  96693. document.addEventListener("keydown", this._onKeyDown);
  96694. // Exiting VR mode double tapping the touch screen
  96695. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  96696. if (_this.isInVRMode) {
  96697. _this.exitVR();
  96698. if (_this._fullscreenVRpresenting) {
  96699. _this._scene.getEngine().switchFullscreen(true);
  96700. }
  96701. }
  96702. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  96703. // Listen for WebVR display changes
  96704. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  96705. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  96706. this._onVRRequestPresentStart = function () {
  96707. _this._webVRrequesting = true;
  96708. _this.updateButtonVisibility();
  96709. };
  96710. this._onVRRequestPresentComplete = function (success) {
  96711. _this._webVRrequesting = false;
  96712. _this.updateButtonVisibility();
  96713. };
  96714. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  96715. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  96716. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  96717. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96718. scene.onDisposeObservable.add(function () {
  96719. _this.dispose();
  96720. });
  96721. // Gamepad connection events
  96722. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96723. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96724. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96725. this.updateButtonVisibility();
  96726. //create easing functions
  96727. this._circleEase = new BABYLON.CircleEase();
  96728. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96729. if (this.webVROptions.floorMeshes) {
  96730. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96731. }
  96732. }
  96733. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96734. /** Return this.onEnteringVRObservable
  96735. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96736. */
  96737. get: function () {
  96738. return this.onEnteringVRObservable;
  96739. },
  96740. enumerable: true,
  96741. configurable: true
  96742. });
  96743. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96744. /** Return this.onExitingVRObservable
  96745. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96746. */
  96747. get: function () {
  96748. return this.onExitingVRObservable;
  96749. },
  96750. enumerable: true,
  96751. configurable: true
  96752. });
  96753. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96754. /** Return this.onControllerMeshLoadedObservable
  96755. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96756. */
  96757. get: function () {
  96758. return this.onControllerMeshLoadedObservable;
  96759. },
  96760. enumerable: true,
  96761. configurable: true
  96762. });
  96763. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96764. /**
  96765. * The mesh used to display where the user is going to teleport.
  96766. */
  96767. get: function () {
  96768. return this._teleportationTarget;
  96769. },
  96770. /**
  96771. * Sets the mesh to be used to display where the user is going to teleport.
  96772. */
  96773. set: function (value) {
  96774. if (value) {
  96775. value.name = "teleportationTarget";
  96776. this._isDefaultTeleportationTarget = false;
  96777. this._teleportationTarget = value;
  96778. }
  96779. },
  96780. enumerable: true,
  96781. configurable: true
  96782. });
  96783. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  96784. /**
  96785. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  96786. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  96787. * See http://doc.babylonjs.com/resources/baking_transformations
  96788. */
  96789. get: function () {
  96790. return this._cameraGazer._gazeTracker;
  96791. },
  96792. set: function (value) {
  96793. if (value) {
  96794. // Dispose of existing meshes
  96795. if (this._cameraGazer._gazeTracker) {
  96796. this._cameraGazer._gazeTracker.dispose();
  96797. }
  96798. if (this._leftController && this._leftController._gazeTracker) {
  96799. this._leftController._gazeTracker.dispose();
  96800. }
  96801. if (this._rightController && this._rightController._gazeTracker) {
  96802. this._rightController._gazeTracker.dispose();
  96803. }
  96804. // Set and create gaze trackers on head and controllers
  96805. this._cameraGazer._gazeTracker = value;
  96806. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  96807. this._cameraGazer._gazeTracker.isPickable = false;
  96808. this._cameraGazer._gazeTracker.isVisible = false;
  96809. this._cameraGazer._gazeTracker.name = "gazeTracker";
  96810. if (this._leftController) {
  96811. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96812. }
  96813. if (this._rightController) {
  96814. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96815. }
  96816. }
  96817. },
  96818. enumerable: true,
  96819. configurable: true
  96820. });
  96821. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  96822. /**
  96823. * The gaze tracking mesh corresponding to the left controller
  96824. */
  96825. get: function () {
  96826. if (this._leftController) {
  96827. return this._leftController._gazeTracker;
  96828. }
  96829. return null;
  96830. },
  96831. enumerable: true,
  96832. configurable: true
  96833. });
  96834. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  96835. /**
  96836. * The gaze tracking mesh corresponding to the right controller
  96837. */
  96838. get: function () {
  96839. if (this._rightController) {
  96840. return this._rightController._gazeTracker;
  96841. }
  96842. return null;
  96843. },
  96844. enumerable: true,
  96845. configurable: true
  96846. });
  96847. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  96848. /**
  96849. * If the ray of the gaze should be displayed.
  96850. */
  96851. get: function () {
  96852. return this._displayGaze;
  96853. },
  96854. /**
  96855. * Sets if the ray of the gaze should be displayed.
  96856. */
  96857. set: function (value) {
  96858. this._displayGaze = value;
  96859. if (!value) {
  96860. this._cameraGazer._gazeTracker.isVisible = false;
  96861. if (this._leftController) {
  96862. this._leftController._gazeTracker.isVisible = false;
  96863. }
  96864. if (this._rightController) {
  96865. this._rightController._gazeTracker.isVisible = false;
  96866. }
  96867. }
  96868. },
  96869. enumerable: true,
  96870. configurable: true
  96871. });
  96872. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  96873. /**
  96874. * If the ray of the LaserPointer should be displayed.
  96875. */
  96876. get: function () {
  96877. return this._displayLaserPointer;
  96878. },
  96879. /**
  96880. * Sets if the ray of the LaserPointer should be displayed.
  96881. */
  96882. set: function (value) {
  96883. this._displayLaserPointer = value;
  96884. if (!value) {
  96885. if (this._rightController) {
  96886. this._rightController._deactivatePointer();
  96887. this._rightController._gazeTracker.isVisible = false;
  96888. }
  96889. if (this._leftController) {
  96890. this._leftController._deactivatePointer();
  96891. this._leftController._gazeTracker.isVisible = false;
  96892. }
  96893. }
  96894. else {
  96895. if (this._rightController) {
  96896. this._rightController._activatePointer();
  96897. }
  96898. if (this._leftController) {
  96899. this._leftController._activatePointer();
  96900. }
  96901. }
  96902. },
  96903. enumerable: true,
  96904. configurable: true
  96905. });
  96906. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  96907. /**
  96908. * The deviceOrientationCamera used as the camera when not in VR.
  96909. */
  96910. get: function () {
  96911. return this._deviceOrientationCamera;
  96912. },
  96913. enumerable: true,
  96914. configurable: true
  96915. });
  96916. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  96917. /**
  96918. * Based on the current WebVR support, returns the current VR camera used.
  96919. */
  96920. get: function () {
  96921. if (this._webVRready) {
  96922. return this._webVRCamera;
  96923. }
  96924. else {
  96925. return this._scene.activeCamera;
  96926. }
  96927. },
  96928. enumerable: true,
  96929. configurable: true
  96930. });
  96931. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  96932. /**
  96933. * The webVRCamera which is used when in VR.
  96934. */
  96935. get: function () {
  96936. return this._webVRCamera;
  96937. },
  96938. enumerable: true,
  96939. configurable: true
  96940. });
  96941. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  96942. /**
  96943. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  96944. */
  96945. get: function () {
  96946. return this._vrDeviceOrientationCamera;
  96947. },
  96948. enumerable: true,
  96949. configurable: true
  96950. });
  96951. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  96952. get: function () {
  96953. var result = this._cameraGazer._teleportationRequestInitiated
  96954. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  96955. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  96956. return result;
  96957. },
  96958. enumerable: true,
  96959. configurable: true
  96960. });
  96961. // Raised when one of the controller has loaded successfully its associated default mesh
  96962. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  96963. if (this._leftController && this._leftController.webVRController == webVRController) {
  96964. if (webVRController.mesh) {
  96965. this._leftController._setLaserPointerParent(webVRController.mesh);
  96966. }
  96967. }
  96968. if (this._rightController && this._rightController.webVRController == webVRController) {
  96969. if (webVRController.mesh) {
  96970. this._rightController._setLaserPointerParent(webVRController.mesh);
  96971. }
  96972. }
  96973. try {
  96974. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  96975. }
  96976. catch (err) {
  96977. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  96978. }
  96979. };
  96980. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  96981. /**
  96982. * Gets a value indicating if we are currently in VR mode.
  96983. */
  96984. get: function () {
  96985. return this._webVRpresenting || this._fullscreenVRpresenting;
  96986. },
  96987. enumerable: true,
  96988. configurable: true
  96989. });
  96990. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  96991. var vrDisplay = this._scene.getEngine().getVRDevice();
  96992. if (vrDisplay) {
  96993. var wasPresenting = this._webVRpresenting;
  96994. this._webVRpresenting = vrDisplay.isPresenting;
  96995. if (wasPresenting && !this._webVRpresenting)
  96996. this.exitVR();
  96997. }
  96998. else {
  96999. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  97000. }
  97001. this.updateButtonVisibility();
  97002. };
  97003. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  97004. this._webVRsupported = eventArgs.vrSupported;
  97005. this._webVRready = !!eventArgs.vrDisplay;
  97006. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  97007. this.updateButtonVisibility();
  97008. };
  97009. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  97010. if (this._canvas && !this._useCustomVRButton) {
  97011. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  97012. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  97013. }
  97014. };
  97015. VRExperienceHelper.prototype.displayVRButton = function () {
  97016. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  97017. document.body.appendChild(this._btnVR);
  97018. this._btnVRDisplayed = true;
  97019. }
  97020. };
  97021. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  97022. if (!this._btnVR || this._useCustomVRButton) {
  97023. return;
  97024. }
  97025. this._btnVR.className = "babylonVRicon";
  97026. if (this.isInVRMode) {
  97027. this._btnVR.className += " vrdisplaypresenting";
  97028. }
  97029. else {
  97030. if (this._webVRready)
  97031. this._btnVR.className += " vrdisplayready";
  97032. if (this._webVRsupported)
  97033. this._btnVR.className += " vrdisplaysupported";
  97034. if (this._webVRrequesting)
  97035. this._btnVR.className += " vrdisplayrequesting";
  97036. }
  97037. };
  97038. /**
  97039. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  97040. * Otherwise, will use the fullscreen API.
  97041. */
  97042. VRExperienceHelper.prototype.enterVR = function () {
  97043. if (this.onEnteringVRObservable) {
  97044. try {
  97045. this.onEnteringVRObservable.notifyObservers(this);
  97046. }
  97047. catch (err) {
  97048. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  97049. }
  97050. }
  97051. if (this._scene.activeCamera) {
  97052. this._position = this._scene.activeCamera.position.clone();
  97053. // make sure that we return to the last active camera
  97054. this._existingCamera = this._scene.activeCamera;
  97055. }
  97056. if (this._webVRrequesting)
  97057. return;
  97058. // If WebVR is supported and a headset is connected
  97059. if (this._webVRready) {
  97060. if (!this._webVRpresenting) {
  97061. this._webVRCamera.position = this._position;
  97062. this._scene.activeCamera = this._webVRCamera;
  97063. }
  97064. }
  97065. else if (this._vrDeviceOrientationCamera) {
  97066. this._vrDeviceOrientationCamera.position = this._position;
  97067. if (this._scene.activeCamera) {
  97068. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97069. }
  97070. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  97071. this._scene.getEngine().switchFullscreen(true);
  97072. this.updateButtonVisibility();
  97073. }
  97074. if (this._scene.activeCamera && this._canvas) {
  97075. this._scene.activeCamera.attachControl(this._canvas);
  97076. }
  97077. if (this._interactionsEnabled) {
  97078. this._scene.registerBeforeRender(this.beforeRender);
  97079. }
  97080. this._hasEnteredVR = true;
  97081. };
  97082. /**
  97083. * Attempt to exit VR, or fullscreen.
  97084. */
  97085. VRExperienceHelper.prototype.exitVR = function () {
  97086. if (this._hasEnteredVR) {
  97087. if (this.onExitingVRObservable) {
  97088. try {
  97089. this.onExitingVRObservable.notifyObservers(this);
  97090. }
  97091. catch (err) {
  97092. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  97093. }
  97094. }
  97095. if (this._webVRpresenting) {
  97096. this._scene.getEngine().disableVR();
  97097. }
  97098. if (this._scene.activeCamera) {
  97099. this._position = this._scene.activeCamera.position.clone();
  97100. }
  97101. if (this._deviceOrientationCamera) {
  97102. this._deviceOrientationCamera.position = this._position;
  97103. this._scene.activeCamera = this._deviceOrientationCamera;
  97104. if (this._canvas) {
  97105. this._scene.activeCamera.attachControl(this._canvas);
  97106. }
  97107. }
  97108. else if (this._existingCamera) {
  97109. this._existingCamera.position = this._position;
  97110. this._scene.activeCamera = this._existingCamera;
  97111. }
  97112. this.updateButtonVisibility();
  97113. if (this._interactionsEnabled) {
  97114. this._scene.unregisterBeforeRender(this.beforeRender);
  97115. this._cameraGazer._gazeTracker.isVisible = false;
  97116. if (this._leftController) {
  97117. this._leftController._gazeTracker.isVisible = false;
  97118. }
  97119. if (this._rightController) {
  97120. this._rightController._gazeTracker.isVisible = false;
  97121. }
  97122. }
  97123. // resize to update width and height when exiting vr exits fullscreen
  97124. this._scene.getEngine().resize();
  97125. this._hasEnteredVR = false;
  97126. }
  97127. };
  97128. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  97129. /**
  97130. * The position of the vr experience helper.
  97131. */
  97132. get: function () {
  97133. return this._position;
  97134. },
  97135. /**
  97136. * Sets the position of the vr experience helper.
  97137. */
  97138. set: function (value) {
  97139. this._position = value;
  97140. if (this._scene.activeCamera) {
  97141. this._scene.activeCamera.position = value;
  97142. }
  97143. },
  97144. enumerable: true,
  97145. configurable: true
  97146. });
  97147. /**
  97148. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  97149. */
  97150. VRExperienceHelper.prototype.enableInteractions = function () {
  97151. var _this = this;
  97152. if (!this._interactionsEnabled) {
  97153. this._interactionsRequested = true;
  97154. if (this._leftController) {
  97155. this._enableInteractionOnController(this._leftController);
  97156. }
  97157. if (this._rightController) {
  97158. this._enableInteractionOnController(this._rightController);
  97159. }
  97160. this.raySelectionPredicate = function (mesh) {
  97161. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  97162. };
  97163. this.meshSelectionPredicate = function (mesh) {
  97164. return true;
  97165. };
  97166. this._raySelectionPredicate = function (mesh) {
  97167. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  97168. && mesh.name.indexOf("teleportationTarget") === -1
  97169. && mesh.name.indexOf("torusTeleportation") === -1)) {
  97170. return _this.raySelectionPredicate(mesh);
  97171. }
  97172. return false;
  97173. };
  97174. this._interactionsEnabled = true;
  97175. }
  97176. };
  97177. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  97178. get: function () {
  97179. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  97180. },
  97181. enumerable: true,
  97182. configurable: true
  97183. });
  97184. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  97185. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  97186. if (this._floorMeshesCollection[i].id === mesh.id) {
  97187. return true;
  97188. }
  97189. }
  97190. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  97191. return true;
  97192. }
  97193. return false;
  97194. };
  97195. /**
  97196. * Adds a floor mesh to be used for teleportation.
  97197. * @param floorMesh the mesh to be used for teleportation.
  97198. */
  97199. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  97200. if (!this._floorMeshesCollection) {
  97201. return;
  97202. }
  97203. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  97204. return;
  97205. }
  97206. this._floorMeshesCollection.push(floorMesh);
  97207. };
  97208. /**
  97209. * Removes a floor mesh from being used for teleportation.
  97210. * @param floorMesh the mesh to be removed.
  97211. */
  97212. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  97213. if (!this._floorMeshesCollection) {
  97214. return;
  97215. }
  97216. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  97217. if (meshIndex !== -1) {
  97218. this._floorMeshesCollection.splice(meshIndex, 1);
  97219. }
  97220. };
  97221. /**
  97222. * Enables interactions and teleportation using the VR controllers and gaze.
  97223. * @param vrTeleportationOptions options to modify teleportation behavior.
  97224. */
  97225. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  97226. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  97227. if (!this._teleportationInitialized) {
  97228. this._teleportationRequested = true;
  97229. this.enableInteractions();
  97230. if (vrTeleportationOptions.floorMeshName) {
  97231. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  97232. }
  97233. if (vrTeleportationOptions.floorMeshes) {
  97234. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  97235. }
  97236. if (this._leftController != null) {
  97237. this._enableTeleportationOnController(this._leftController);
  97238. }
  97239. if (this._rightController != null) {
  97240. this._enableTeleportationOnController(this._rightController);
  97241. }
  97242. // Creates an image processing post process for the vignette not relying
  97243. // on the main scene configuration for image processing to reduce setup and spaces
  97244. // (gamma/linear) conflicts.
  97245. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  97246. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  97247. imageProcessingConfiguration.vignetteEnabled = true;
  97248. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  97249. this._webVRCamera.detachPostProcess(this._postProcessMove);
  97250. this._teleportationInitialized = true;
  97251. if (this._isDefaultTeleportationTarget) {
  97252. this._createTeleportationCircles();
  97253. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  97254. }
  97255. }
  97256. };
  97257. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  97258. var _this = this;
  97259. var controllerMesh = controller.webVRController.mesh;
  97260. if (controllerMesh) {
  97261. controller._interactionsEnabled = true;
  97262. controller._activatePointer();
  97263. if (this.webVROptions.laserToggle) {
  97264. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  97265. // Enabling / disabling laserPointer
  97266. if (_this._displayLaserPointer && stateObject.value === 1) {
  97267. if (controller._activePointer) {
  97268. controller._deactivatePointer();
  97269. }
  97270. else {
  97271. controller._activatePointer();
  97272. }
  97273. if (_this.displayGaze) {
  97274. controller._gazeTracker.isVisible = controller._activePointer;
  97275. }
  97276. }
  97277. });
  97278. }
  97279. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  97280. var gazer = controller;
  97281. if (_this._noControllerIsActive) {
  97282. gazer = _this._cameraGazer;
  97283. }
  97284. if (!gazer._pointerDownOnMeshAsked) {
  97285. if (stateObject.value > _this._padSensibilityUp) {
  97286. gazer._selectionPointerDown();
  97287. }
  97288. }
  97289. else if (stateObject.value < _this._padSensibilityDown) {
  97290. gazer._selectionPointerUp();
  97291. }
  97292. });
  97293. }
  97294. };
  97295. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  97296. // Dont teleport if another gaze already requested teleportation
  97297. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  97298. return;
  97299. }
  97300. if (!gazer._teleportationRequestInitiated) {
  97301. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  97302. gazer._activatePointer();
  97303. gazer._teleportationRequestInitiated = true;
  97304. }
  97305. }
  97306. else {
  97307. // Listening to the proper controller values changes to confirm teleportation
  97308. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  97309. if (this._teleportActive) {
  97310. this._teleportCamera(this._haloCenter);
  97311. }
  97312. gazer._teleportationRequestInitiated = false;
  97313. }
  97314. }
  97315. };
  97316. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  97317. // Only rotate when user is not currently selecting a teleportation location
  97318. if (gazer._teleportationRequestInitiated) {
  97319. return;
  97320. }
  97321. if (!gazer._rotationLeftAsked) {
  97322. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  97323. gazer._rotationLeftAsked = true;
  97324. if (this._rotationAllowed) {
  97325. this._rotateCamera(false);
  97326. }
  97327. }
  97328. }
  97329. else {
  97330. if (stateObject.x > -this._padSensibilityDown) {
  97331. gazer._rotationLeftAsked = false;
  97332. }
  97333. }
  97334. if (!gazer._rotationRightAsked) {
  97335. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  97336. gazer._rotationRightAsked = true;
  97337. if (this._rotationAllowed) {
  97338. this._rotateCamera(true);
  97339. }
  97340. }
  97341. }
  97342. else {
  97343. if (stateObject.x < this._padSensibilityDown) {
  97344. gazer._rotationRightAsked = false;
  97345. }
  97346. }
  97347. };
  97348. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  97349. // Only teleport backwards when user is not currently selecting a teleportation location
  97350. if (gazer._teleportationRequestInitiated) {
  97351. return;
  97352. }
  97353. // Teleport backwards
  97354. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  97355. if (!gazer._teleportationBackRequestInitiated) {
  97356. if (!this.currentVRCamera) {
  97357. return;
  97358. }
  97359. // Get rotation and position of the current camera
  97360. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  97361. var position = this.currentVRCamera.position;
  97362. // If the camera has device position, use that instead
  97363. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  97364. rotation = this.currentVRCamera.deviceRotationQuaternion;
  97365. position = this.currentVRCamera.devicePosition;
  97366. }
  97367. // Get matrix with only the y rotation of the device rotation
  97368. rotation.toEulerAnglesToRef(this._workingVector);
  97369. this._workingVector.z = 0;
  97370. this._workingVector.x = 0;
  97371. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  97372. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  97373. // Rotate backwards ray by device rotation to cast at the ground behind the user
  97374. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  97375. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  97376. var ray = new BABYLON.Ray(position, this._workingVector);
  97377. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97378. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  97379. this._teleportCamera(hit.pickedPoint);
  97380. }
  97381. gazer._teleportationBackRequestInitiated = true;
  97382. }
  97383. }
  97384. else {
  97385. gazer._teleportationBackRequestInitiated = false;
  97386. }
  97387. };
  97388. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  97389. var _this = this;
  97390. var controllerMesh = controller.webVRController.mesh;
  97391. if (controllerMesh) {
  97392. if (!controller._interactionsEnabled) {
  97393. this._enableInteractionOnController(controller);
  97394. }
  97395. controller._interactionsEnabled = true;
  97396. controller._teleportationEnabled = true;
  97397. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97398. controller._dpadPressed = false;
  97399. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  97400. controller._dpadPressed = stateObject.pressed;
  97401. if (!controller._dpadPressed) {
  97402. controller._rotationLeftAsked = false;
  97403. controller._rotationRightAsked = false;
  97404. controller._teleportationBackRequestInitiated = false;
  97405. }
  97406. });
  97407. }
  97408. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  97409. if (_this.teleportationEnabled) {
  97410. _this._checkTeleportBackwards(stateObject, controller);
  97411. _this._checkTeleportWithRay(stateObject, controller);
  97412. }
  97413. _this._checkRotate(stateObject, controller);
  97414. });
  97415. }
  97416. };
  97417. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  97418. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  97419. this._teleportationTarget.isPickable = false;
  97420. var length = 512;
  97421. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  97422. dynamicTexture.hasAlpha = true;
  97423. var context = dynamicTexture.getContext();
  97424. var centerX = length / 2;
  97425. var centerY = length / 2;
  97426. var radius = 200;
  97427. context.beginPath();
  97428. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  97429. context.fillStyle = this._teleportationFillColor;
  97430. context.fill();
  97431. context.lineWidth = 10;
  97432. context.strokeStyle = this._teleportationBorderColor;
  97433. context.stroke();
  97434. context.closePath();
  97435. dynamicTexture.update();
  97436. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  97437. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  97438. this._teleportationTarget.material = teleportationCircleMaterial;
  97439. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  97440. torus.isPickable = false;
  97441. torus.parent = this._teleportationTarget;
  97442. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  97443. var keys = [];
  97444. keys.push({
  97445. frame: 0,
  97446. value: 0
  97447. });
  97448. keys.push({
  97449. frame: 30,
  97450. value: 0.4
  97451. });
  97452. keys.push({
  97453. frame: 60,
  97454. value: 0
  97455. });
  97456. animationInnerCircle.setKeys(keys);
  97457. var easingFunction = new BABYLON.SineEase();
  97458. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97459. animationInnerCircle.setEasingFunction(easingFunction);
  97460. torus.animations = [];
  97461. torus.animations.push(animationInnerCircle);
  97462. this._scene.beginAnimation(torus, 0, 60, true);
  97463. this._hideTeleportationTarget();
  97464. };
  97465. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  97466. this._teleportActive = true;
  97467. if (this._teleportationInitialized) {
  97468. this._teleportationTarget.isVisible = true;
  97469. if (this._isDefaultTeleportationTarget) {
  97470. this._teleportationTarget.getChildren()[0].isVisible = true;
  97471. }
  97472. }
  97473. };
  97474. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  97475. this._teleportActive = false;
  97476. if (this._teleportationInitialized) {
  97477. this._teleportationTarget.isVisible = false;
  97478. if (this._isDefaultTeleportationTarget) {
  97479. this._teleportationTarget.getChildren()[0].isVisible = false;
  97480. }
  97481. }
  97482. };
  97483. VRExperienceHelper.prototype._rotateCamera = function (right) {
  97484. var _this = this;
  97485. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97486. return;
  97487. }
  97488. if (right) {
  97489. this._rotationAngle++;
  97490. }
  97491. else {
  97492. this._rotationAngle--;
  97493. }
  97494. this.currentVRCamera.animations = [];
  97495. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  97496. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97497. var animationRotationKeys = [];
  97498. animationRotationKeys.push({
  97499. frame: 0,
  97500. value: this.currentVRCamera.rotationQuaternion
  97501. });
  97502. animationRotationKeys.push({
  97503. frame: 6,
  97504. value: target
  97505. });
  97506. animationRotation.setKeys(animationRotationKeys);
  97507. animationRotation.setEasingFunction(this._circleEase);
  97508. this.currentVRCamera.animations.push(animationRotation);
  97509. this._postProcessMove.animations = [];
  97510. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97511. var vignetteWeightKeys = [];
  97512. vignetteWeightKeys.push({
  97513. frame: 0,
  97514. value: 0
  97515. });
  97516. vignetteWeightKeys.push({
  97517. frame: 3,
  97518. value: 4
  97519. });
  97520. vignetteWeightKeys.push({
  97521. frame: 6,
  97522. value: 0
  97523. });
  97524. animationPP.setKeys(vignetteWeightKeys);
  97525. animationPP.setEasingFunction(this._circleEase);
  97526. this._postProcessMove.animations.push(animationPP);
  97527. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97528. var vignetteStretchKeys = [];
  97529. vignetteStretchKeys.push({
  97530. frame: 0,
  97531. value: 0
  97532. });
  97533. vignetteStretchKeys.push({
  97534. frame: 3,
  97535. value: 10
  97536. });
  97537. vignetteStretchKeys.push({
  97538. frame: 6,
  97539. value: 0
  97540. });
  97541. animationPP2.setKeys(vignetteStretchKeys);
  97542. animationPP2.setEasingFunction(this._circleEase);
  97543. this._postProcessMove.animations.push(animationPP2);
  97544. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97545. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97546. this._postProcessMove.samples = 4;
  97547. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97548. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  97549. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97550. });
  97551. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  97552. };
  97553. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  97554. if (hit.pickedPoint) {
  97555. if (gazer._teleportationRequestInitiated) {
  97556. this._displayTeleportationTarget();
  97557. this._haloCenter.copyFrom(hit.pickedPoint);
  97558. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  97559. }
  97560. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  97561. if (pickNormal) {
  97562. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97563. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97564. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  97565. }
  97566. this._teleportationTarget.position.y += 0.1;
  97567. }
  97568. };
  97569. VRExperienceHelper.prototype._teleportCamera = function (location) {
  97570. var _this = this;
  97571. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97572. return;
  97573. }
  97574. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  97575. // offset of the headset from the anchor.
  97576. if (this.webVRCamera.leftCamera) {
  97577. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  97578. this._workingVector.subtractInPlace(this.webVRCamera.position);
  97579. location.subtractToRef(this._workingVector, this._workingVector);
  97580. }
  97581. else {
  97582. this._workingVector.copyFrom(location);
  97583. }
  97584. // Add height to account for user's height offset
  97585. if (this.isInVRMode) {
  97586. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  97587. }
  97588. else {
  97589. this._workingVector.y += this._defaultHeight;
  97590. }
  97591. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  97592. // Create animation from the camera's position to the new location
  97593. this.currentVRCamera.animations = [];
  97594. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97595. var animationCameraTeleportationKeys = [{
  97596. frame: 0,
  97597. value: this.currentVRCamera.position
  97598. },
  97599. {
  97600. frame: 11,
  97601. value: this._workingVector
  97602. }
  97603. ];
  97604. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  97605. animationCameraTeleportation.setEasingFunction(this._circleEase);
  97606. this.currentVRCamera.animations.push(animationCameraTeleportation);
  97607. this._postProcessMove.animations = [];
  97608. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97609. var vignetteWeightKeys = [];
  97610. vignetteWeightKeys.push({
  97611. frame: 0,
  97612. value: 0
  97613. });
  97614. vignetteWeightKeys.push({
  97615. frame: 5,
  97616. value: 8
  97617. });
  97618. vignetteWeightKeys.push({
  97619. frame: 11,
  97620. value: 0
  97621. });
  97622. animationPP.setKeys(vignetteWeightKeys);
  97623. this._postProcessMove.animations.push(animationPP);
  97624. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97625. var vignetteStretchKeys = [];
  97626. vignetteStretchKeys.push({
  97627. frame: 0,
  97628. value: 0
  97629. });
  97630. vignetteStretchKeys.push({
  97631. frame: 5,
  97632. value: 10
  97633. });
  97634. vignetteStretchKeys.push({
  97635. frame: 11,
  97636. value: 0
  97637. });
  97638. animationPP2.setKeys(vignetteStretchKeys);
  97639. this._postProcessMove.animations.push(animationPP2);
  97640. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97641. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97642. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97643. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  97644. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97645. });
  97646. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  97647. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  97648. });
  97649. this._hideTeleportationTarget();
  97650. };
  97651. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  97652. if (normal) {
  97653. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  97654. if (angle < Math.PI / 2) {
  97655. normal.scaleInPlace(-1);
  97656. }
  97657. }
  97658. return normal;
  97659. };
  97660. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  97661. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97662. return;
  97663. }
  97664. var ray = gazer._getForwardRay(this._rayLength);
  97665. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97666. if (hit) {
  97667. // Populate the contrllers mesh that can be used for drag/drop
  97668. if (gazer._laserPointer) {
  97669. hit.originMesh = gazer._laserPointer.parent;
  97670. }
  97671. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  97672. }
  97673. gazer._currentHit = hit;
  97674. // Moving the gazeTracker on the mesh face targetted
  97675. if (hit && hit.pickedPoint) {
  97676. if (this._displayGaze) {
  97677. var multiplier = 1;
  97678. gazer._gazeTracker.isVisible = true;
  97679. if (gazer._isActionableMesh) {
  97680. multiplier = 3;
  97681. }
  97682. if (this.updateGazeTrackerScale) {
  97683. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  97684. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  97685. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  97686. }
  97687. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  97688. // To avoid z-fighting
  97689. var deltaFighting = 0.002;
  97690. if (pickNormal) {
  97691. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97692. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97693. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  97694. }
  97695. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  97696. if (gazer._gazeTracker.position.x < 0) {
  97697. gazer._gazeTracker.position.x += deltaFighting;
  97698. }
  97699. else {
  97700. gazer._gazeTracker.position.x -= deltaFighting;
  97701. }
  97702. if (gazer._gazeTracker.position.y < 0) {
  97703. gazer._gazeTracker.position.y += deltaFighting;
  97704. }
  97705. else {
  97706. gazer._gazeTracker.position.y -= deltaFighting;
  97707. }
  97708. if (gazer._gazeTracker.position.z < 0) {
  97709. gazer._gazeTracker.position.z += deltaFighting;
  97710. }
  97711. else {
  97712. gazer._gazeTracker.position.z -= deltaFighting;
  97713. }
  97714. }
  97715. // Changing the size of the laser pointer based on the distance from the targetted point
  97716. gazer._updatePointerDistance(hit.distance);
  97717. }
  97718. else {
  97719. gazer._updatePointerDistance();
  97720. gazer._gazeTracker.isVisible = false;
  97721. }
  97722. if (hit && hit.pickedMesh) {
  97723. // The object selected is the floor, we're in a teleportation scenario
  97724. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97725. // Moving the teleportation area to this targetted point
  97726. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97727. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97728. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97729. }
  97730. gazer._currentMeshSelected = null;
  97731. if (gazer._teleportationRequestInitiated) {
  97732. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97733. }
  97734. return;
  97735. }
  97736. // If not, we're in a selection scenario
  97737. //this._teleportationAllowed = false;
  97738. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97739. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97740. this.onNewMeshPicked.notifyObservers(hit);
  97741. gazer._currentMeshSelected = hit.pickedMesh;
  97742. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97743. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97744. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97745. gazer._isActionableMesh = true;
  97746. }
  97747. else {
  97748. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97749. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97750. gazer._isActionableMesh = false;
  97751. }
  97752. try {
  97753. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97754. }
  97755. catch (err) {
  97756. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97757. }
  97758. }
  97759. else {
  97760. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97761. gazer._currentMeshSelected = null;
  97762. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97763. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97764. }
  97765. }
  97766. }
  97767. else {
  97768. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97769. gazer._currentMeshSelected = null;
  97770. //this._teleportationAllowed = false;
  97771. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97772. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97773. }
  97774. };
  97775. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  97776. if (mesh) {
  97777. this.onSelectedMeshUnselected.notifyObservers(mesh);
  97778. }
  97779. };
  97780. /**
  97781. * Sets the color of the laser ray from the vr controllers.
  97782. * @param color new color for the ray.
  97783. */
  97784. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  97785. if (this._leftController) {
  97786. this._leftController._setLaserPointerColor(color);
  97787. }
  97788. if (this._rightController) {
  97789. this._rightController._setLaserPointerColor(color);
  97790. }
  97791. };
  97792. /**
  97793. * Sets the color of the ray from the vr headsets gaze.
  97794. * @param color new color for the ray.
  97795. */
  97796. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  97797. if (!this._cameraGazer._gazeTracker.material) {
  97798. return;
  97799. }
  97800. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  97801. if (this._leftController) {
  97802. this._leftController._gazeTracker.material.emissiveColor = color;
  97803. }
  97804. if (this._rightController) {
  97805. this._rightController._gazeTracker.material.emissiveColor = color;
  97806. }
  97807. };
  97808. /**
  97809. * Exits VR and disposes of the vr experience helper
  97810. */
  97811. VRExperienceHelper.prototype.dispose = function () {
  97812. if (this.isInVRMode) {
  97813. this.exitVR();
  97814. }
  97815. if (this._postProcessMove) {
  97816. this._postProcessMove.dispose();
  97817. }
  97818. if (this._webVRCamera) {
  97819. this._webVRCamera.dispose();
  97820. }
  97821. if (this._vrDeviceOrientationCamera) {
  97822. this._vrDeviceOrientationCamera.dispose();
  97823. }
  97824. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  97825. document.body.removeChild(this._btnVR);
  97826. }
  97827. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  97828. this._deviceOrientationCamera.dispose();
  97829. }
  97830. if (this._cameraGazer) {
  97831. this._cameraGazer.dispose();
  97832. }
  97833. if (this._leftController) {
  97834. this._leftController.dispose();
  97835. }
  97836. if (this._rightController) {
  97837. this._rightController.dispose();
  97838. }
  97839. if (this._teleportationTarget) {
  97840. this._teleportationTarget.dispose();
  97841. }
  97842. this._floorMeshesCollection = [];
  97843. document.removeEventListener("keydown", this._onKeyDown);
  97844. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97845. window.removeEventListener("resize", this._onResize);
  97846. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  97847. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  97848. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  97849. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  97850. document.onmsfullscreenchange = null;
  97851. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  97852. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  97853. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  97854. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97855. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  97856. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  97857. this._scene.unregisterBeforeRender(this.beforeRender);
  97858. };
  97859. /**
  97860. * Gets the name of the VRExperienceHelper class
  97861. * @returns "VRExperienceHelper"
  97862. */
  97863. VRExperienceHelper.prototype.getClassName = function () {
  97864. return "VRExperienceHelper";
  97865. };
  97866. return VRExperienceHelper;
  97867. }());
  97868. BABYLON.VRExperienceHelper = VRExperienceHelper;
  97869. })(BABYLON || (BABYLON = {}));
  97870. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  97871. // Mainly based on these 2 articles :
  97872. // 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
  97873. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  97874. var BABYLON;
  97875. (function (BABYLON) {
  97876. /**
  97877. * Defines the potential axis of a Joystick
  97878. */
  97879. var JoystickAxis;
  97880. (function (JoystickAxis) {
  97881. /** X axis */
  97882. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  97883. /** Y axis */
  97884. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  97885. /** Z axis */
  97886. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  97887. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  97888. /**
  97889. * Class used to define virtual joystick (used in touch mode)
  97890. */
  97891. var VirtualJoystick = /** @class */ (function () {
  97892. /**
  97893. * Creates a new virtual joystick
  97894. * @param leftJoystick defines that the joystick is for left hand (false by default)
  97895. */
  97896. function VirtualJoystick(leftJoystick) {
  97897. var _this = this;
  97898. if (leftJoystick) {
  97899. this._leftJoystick = true;
  97900. }
  97901. else {
  97902. this._leftJoystick = false;
  97903. }
  97904. VirtualJoystick._globalJoystickIndex++;
  97905. // By default left & right arrow keys are moving the X
  97906. // and up & down keys are moving the Y
  97907. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97908. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97909. this.reverseLeftRight = false;
  97910. this.reverseUpDown = false;
  97911. // collections of pointers
  97912. this._touches = new BABYLON.StringDictionary();
  97913. this.deltaPosition = BABYLON.Vector3.Zero();
  97914. this._joystickSensibility = 25;
  97915. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97916. this._onResize = function (evt) {
  97917. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97918. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97919. if (VirtualJoystick.vjCanvas) {
  97920. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  97921. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  97922. }
  97923. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  97924. };
  97925. // injecting a canvas element on top of the canvas 3D game
  97926. if (!VirtualJoystick.vjCanvas) {
  97927. window.addEventListener("resize", this._onResize, false);
  97928. VirtualJoystick.vjCanvas = document.createElement("canvas");
  97929. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97930. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97931. VirtualJoystick.vjCanvas.width = window.innerWidth;
  97932. VirtualJoystick.vjCanvas.height = window.innerHeight;
  97933. VirtualJoystick.vjCanvas.style.width = "100%";
  97934. VirtualJoystick.vjCanvas.style.height = "100%";
  97935. VirtualJoystick.vjCanvas.style.position = "absolute";
  97936. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  97937. VirtualJoystick.vjCanvas.style.top = "0px";
  97938. VirtualJoystick.vjCanvas.style.left = "0px";
  97939. VirtualJoystick.vjCanvas.style.zIndex = "5";
  97940. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  97941. // Support for jQuery PEP polyfill
  97942. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  97943. var context = VirtualJoystick.vjCanvas.getContext('2d');
  97944. if (!context) {
  97945. throw new Error("Unable to create canvas for virtual joystick");
  97946. }
  97947. VirtualJoystick.vjCanvasContext = context;
  97948. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  97949. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97950. document.body.appendChild(VirtualJoystick.vjCanvas);
  97951. }
  97952. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  97953. this.pressed = false;
  97954. // default joystick color
  97955. this._joystickColor = "cyan";
  97956. this._joystickPointerID = -1;
  97957. // current joystick position
  97958. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  97959. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  97960. // origin joystick position
  97961. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  97962. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  97963. this._onPointerDownHandlerRef = function (evt) {
  97964. _this._onPointerDown(evt);
  97965. };
  97966. this._onPointerMoveHandlerRef = function (evt) {
  97967. _this._onPointerMove(evt);
  97968. };
  97969. this._onPointerUpHandlerRef = function (evt) {
  97970. _this._onPointerUp(evt);
  97971. };
  97972. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  97973. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  97974. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  97975. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  97976. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  97977. evt.preventDefault(); // Disables system menu
  97978. }, false);
  97979. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97980. }
  97981. /**
  97982. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  97983. * @param newJoystickSensibility defines the new sensibility
  97984. */
  97985. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  97986. this._joystickSensibility = newJoystickSensibility;
  97987. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97988. };
  97989. VirtualJoystick.prototype._onPointerDown = function (e) {
  97990. var positionOnScreenCondition;
  97991. e.preventDefault();
  97992. if (this._leftJoystick === true) {
  97993. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  97994. }
  97995. else {
  97996. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  97997. }
  97998. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  97999. // First contact will be dedicated to the virtual joystick
  98000. this._joystickPointerID = e.pointerId;
  98001. this._joystickPointerStartPos.x = e.clientX;
  98002. this._joystickPointerStartPos.y = e.clientY;
  98003. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  98004. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  98005. this._deltaJoystickVector.x = 0;
  98006. this._deltaJoystickVector.y = 0;
  98007. this.pressed = true;
  98008. this._touches.add(e.pointerId.toString(), e);
  98009. }
  98010. else {
  98011. // You can only trigger the action buttons with a joystick declared
  98012. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  98013. this._action();
  98014. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  98015. }
  98016. }
  98017. };
  98018. VirtualJoystick.prototype._onPointerMove = function (e) {
  98019. // If the current pointer is the one associated to the joystick (first touch contact)
  98020. if (this._joystickPointerID == e.pointerId) {
  98021. this._joystickPointerPos.x = e.clientX;
  98022. this._joystickPointerPos.y = e.clientY;
  98023. this._deltaJoystickVector = this._joystickPointerPos.clone();
  98024. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  98025. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  98026. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  98027. switch (this._axisTargetedByLeftAndRight) {
  98028. case JoystickAxis.X:
  98029. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  98030. break;
  98031. case JoystickAxis.Y:
  98032. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  98033. break;
  98034. case JoystickAxis.Z:
  98035. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  98036. break;
  98037. }
  98038. var directionUpDown = this.reverseUpDown ? 1 : -1;
  98039. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  98040. switch (this._axisTargetedByUpAndDown) {
  98041. case JoystickAxis.X:
  98042. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  98043. break;
  98044. case JoystickAxis.Y:
  98045. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  98046. break;
  98047. case JoystickAxis.Z:
  98048. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  98049. break;
  98050. }
  98051. }
  98052. else {
  98053. var data = this._touches.get(e.pointerId.toString());
  98054. if (data) {
  98055. data.x = e.clientX;
  98056. data.y = e.clientY;
  98057. }
  98058. }
  98059. };
  98060. VirtualJoystick.prototype._onPointerUp = function (e) {
  98061. if (this._joystickPointerID == e.pointerId) {
  98062. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  98063. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  98064. this._joystickPointerID = -1;
  98065. this.pressed = false;
  98066. }
  98067. else {
  98068. var touch = this._touches.get(e.pointerId.toString());
  98069. if (touch) {
  98070. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98071. }
  98072. }
  98073. this._deltaJoystickVector.x = 0;
  98074. this._deltaJoystickVector.y = 0;
  98075. this._touches.remove(e.pointerId.toString());
  98076. };
  98077. /**
  98078. * Change the color of the virtual joystick
  98079. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  98080. */
  98081. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  98082. this._joystickColor = newColor;
  98083. };
  98084. /**
  98085. * Defines a callback to call when the joystick is touched
  98086. * @param action defines the callback
  98087. */
  98088. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  98089. this._action = action;
  98090. };
  98091. /**
  98092. * Defines which axis you'd like to control for left & right
  98093. * @param axis defines the axis to use
  98094. */
  98095. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  98096. switch (axis) {
  98097. case JoystickAxis.X:
  98098. case JoystickAxis.Y:
  98099. case JoystickAxis.Z:
  98100. this._axisTargetedByLeftAndRight = axis;
  98101. break;
  98102. default:
  98103. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98104. break;
  98105. }
  98106. };
  98107. /**
  98108. * Defines which axis you'd like to control for up & down
  98109. * @param axis defines the axis to use
  98110. */
  98111. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  98112. switch (axis) {
  98113. case JoystickAxis.X:
  98114. case JoystickAxis.Y:
  98115. case JoystickAxis.Z:
  98116. this._axisTargetedByUpAndDown = axis;
  98117. break;
  98118. default:
  98119. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98120. break;
  98121. }
  98122. };
  98123. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  98124. var _this = this;
  98125. if (this.pressed) {
  98126. this._touches.forEach(function (key, touch) {
  98127. if (touch.pointerId === _this._joystickPointerID) {
  98128. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  98129. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  98130. VirtualJoystick.vjCanvasContext.beginPath();
  98131. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  98132. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98133. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  98134. VirtualJoystick.vjCanvasContext.stroke();
  98135. VirtualJoystick.vjCanvasContext.closePath();
  98136. VirtualJoystick.vjCanvasContext.beginPath();
  98137. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98138. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98139. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  98140. VirtualJoystick.vjCanvasContext.stroke();
  98141. VirtualJoystick.vjCanvasContext.closePath();
  98142. VirtualJoystick.vjCanvasContext.beginPath();
  98143. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98144. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  98145. VirtualJoystick.vjCanvasContext.stroke();
  98146. VirtualJoystick.vjCanvasContext.closePath();
  98147. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  98148. }
  98149. else {
  98150. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98151. VirtualJoystick.vjCanvasContext.beginPath();
  98152. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  98153. VirtualJoystick.vjCanvasContext.beginPath();
  98154. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  98155. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  98156. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  98157. VirtualJoystick.vjCanvasContext.stroke();
  98158. VirtualJoystick.vjCanvasContext.closePath();
  98159. touch.prevX = touch.x;
  98160. touch.prevY = touch.y;
  98161. }
  98162. ;
  98163. });
  98164. }
  98165. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98166. };
  98167. /**
  98168. * Release internal HTML canvas
  98169. */
  98170. VirtualJoystick.prototype.releaseCanvas = function () {
  98171. if (VirtualJoystick.vjCanvas) {
  98172. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  98173. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  98174. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  98175. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  98176. window.removeEventListener("resize", this._onResize);
  98177. document.body.removeChild(VirtualJoystick.vjCanvas);
  98178. VirtualJoystick.vjCanvas = null;
  98179. }
  98180. };
  98181. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  98182. VirtualJoystick._globalJoystickIndex = 0;
  98183. return VirtualJoystick;
  98184. }());
  98185. BABYLON.VirtualJoystick = VirtualJoystick;
  98186. })(BABYLON || (BABYLON = {}));
  98187. //# sourceMappingURL=babylon.virtualJoystick.js.map
  98188. var BABYLON;
  98189. (function (BABYLON) {
  98190. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  98191. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  98192. });
  98193. // We're mainly based on the logic defined into the FreeCamera code
  98194. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  98195. __extends(VirtualJoysticksCamera, _super);
  98196. function VirtualJoysticksCamera(name, position, scene) {
  98197. var _this = _super.call(this, name, position, scene) || this;
  98198. _this.inputs.addVirtualJoystick();
  98199. return _this;
  98200. }
  98201. VirtualJoysticksCamera.prototype.getClassName = function () {
  98202. return "VirtualJoysticksCamera";
  98203. };
  98204. return VirtualJoysticksCamera;
  98205. }(BABYLON.FreeCamera));
  98206. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  98207. })(BABYLON || (BABYLON = {}));
  98208. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  98209. var BABYLON;
  98210. (function (BABYLON) {
  98211. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  98212. function FreeCameraVirtualJoystickInput() {
  98213. }
  98214. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  98215. return this._leftjoystick;
  98216. };
  98217. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  98218. return this._rightjoystick;
  98219. };
  98220. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  98221. if (this._leftjoystick) {
  98222. var camera = this.camera;
  98223. var speed = camera._computeLocalCameraSpeed() * 50;
  98224. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  98225. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  98226. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  98227. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  98228. if (!this._leftjoystick.pressed) {
  98229. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  98230. }
  98231. if (!this._rightjoystick.pressed) {
  98232. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  98233. }
  98234. }
  98235. };
  98236. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  98237. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  98238. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  98239. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  98240. this._leftjoystick.setJoystickSensibility(0.15);
  98241. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  98242. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  98243. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  98244. this._rightjoystick.reverseUpDown = true;
  98245. this._rightjoystick.setJoystickSensibility(0.05);
  98246. this._rightjoystick.setJoystickColor("yellow");
  98247. };
  98248. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  98249. this._leftjoystick.releaseCanvas();
  98250. this._rightjoystick.releaseCanvas();
  98251. };
  98252. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  98253. return "FreeCameraVirtualJoystickInput";
  98254. };
  98255. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  98256. return "virtualJoystick";
  98257. };
  98258. return FreeCameraVirtualJoystickInput;
  98259. }());
  98260. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  98261. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  98262. })(BABYLON || (BABYLON = {}));
  98263. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  98264. var BABYLON;
  98265. (function (BABYLON) {
  98266. var SimplificationSettings = /** @class */ (function () {
  98267. function SimplificationSettings(quality, distance, optimizeMesh) {
  98268. this.quality = quality;
  98269. this.distance = distance;
  98270. this.optimizeMesh = optimizeMesh;
  98271. }
  98272. return SimplificationSettings;
  98273. }());
  98274. BABYLON.SimplificationSettings = SimplificationSettings;
  98275. var SimplificationQueue = /** @class */ (function () {
  98276. function SimplificationQueue() {
  98277. this.running = false;
  98278. this._simplificationArray = [];
  98279. }
  98280. SimplificationQueue.prototype.addTask = function (task) {
  98281. this._simplificationArray.push(task);
  98282. };
  98283. SimplificationQueue.prototype.executeNext = function () {
  98284. var task = this._simplificationArray.pop();
  98285. if (task) {
  98286. this.running = true;
  98287. this.runSimplification(task);
  98288. }
  98289. else {
  98290. this.running = false;
  98291. }
  98292. };
  98293. SimplificationQueue.prototype.runSimplification = function (task) {
  98294. var _this = this;
  98295. if (task.parallelProcessing) {
  98296. //parallel simplifier
  98297. task.settings.forEach(function (setting) {
  98298. var simplifier = _this.getSimplifier(task);
  98299. simplifier.simplify(setting, function (newMesh) {
  98300. task.mesh.addLODLevel(setting.distance, newMesh);
  98301. newMesh.isVisible = true;
  98302. //check if it is the last
  98303. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  98304. //all done, run the success callback.
  98305. task.successCallback();
  98306. }
  98307. _this.executeNext();
  98308. });
  98309. });
  98310. }
  98311. else {
  98312. //single simplifier.
  98313. var simplifier = this.getSimplifier(task);
  98314. var runDecimation = function (setting, callback) {
  98315. simplifier.simplify(setting, function (newMesh) {
  98316. task.mesh.addLODLevel(setting.distance, newMesh);
  98317. newMesh.isVisible = true;
  98318. //run the next quality level
  98319. callback();
  98320. });
  98321. };
  98322. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  98323. runDecimation(task.settings[loop.index], function () {
  98324. loop.executeNext();
  98325. });
  98326. }, function () {
  98327. //execution ended, run the success callback.
  98328. if (task.successCallback) {
  98329. task.successCallback();
  98330. }
  98331. _this.executeNext();
  98332. });
  98333. }
  98334. };
  98335. SimplificationQueue.prototype.getSimplifier = function (task) {
  98336. switch (task.simplificationType) {
  98337. case SimplificationType.QUADRATIC:
  98338. default:
  98339. return new QuadraticErrorSimplification(task.mesh);
  98340. }
  98341. };
  98342. return SimplificationQueue;
  98343. }());
  98344. BABYLON.SimplificationQueue = SimplificationQueue;
  98345. /**
  98346. * The implemented types of simplification
  98347. * At the moment only Quadratic Error Decimation is implemented
  98348. */
  98349. var SimplificationType;
  98350. (function (SimplificationType) {
  98351. /** Quadratic error decimation */
  98352. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  98353. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  98354. var DecimationTriangle = /** @class */ (function () {
  98355. function DecimationTriangle(vertices) {
  98356. this.vertices = vertices;
  98357. this.error = new Array(4);
  98358. this.deleted = false;
  98359. this.isDirty = false;
  98360. this.deletePending = false;
  98361. this.borderFactor = 0;
  98362. }
  98363. return DecimationTriangle;
  98364. }());
  98365. BABYLON.DecimationTriangle = DecimationTriangle;
  98366. var DecimationVertex = /** @class */ (function () {
  98367. function DecimationVertex(position, id) {
  98368. this.position = position;
  98369. this.id = id;
  98370. this.isBorder = true;
  98371. this.q = new QuadraticMatrix();
  98372. this.triangleCount = 0;
  98373. this.triangleStart = 0;
  98374. this.originalOffsets = [];
  98375. }
  98376. DecimationVertex.prototype.updatePosition = function (newPosition) {
  98377. this.position.copyFrom(newPosition);
  98378. };
  98379. return DecimationVertex;
  98380. }());
  98381. BABYLON.DecimationVertex = DecimationVertex;
  98382. var QuadraticMatrix = /** @class */ (function () {
  98383. function QuadraticMatrix(data) {
  98384. this.data = new Array(10);
  98385. for (var i = 0; i < 10; ++i) {
  98386. if (data && data[i]) {
  98387. this.data[i] = data[i];
  98388. }
  98389. else {
  98390. this.data[i] = 0;
  98391. }
  98392. }
  98393. }
  98394. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  98395. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  98396. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  98397. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  98398. return det;
  98399. };
  98400. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  98401. for (var i = 0; i < 10; ++i) {
  98402. this.data[i] += matrix.data[i];
  98403. }
  98404. };
  98405. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  98406. for (var i = 0; i < 10; ++i) {
  98407. this.data[i] += data[i];
  98408. }
  98409. };
  98410. QuadraticMatrix.prototype.add = function (matrix) {
  98411. var m = new QuadraticMatrix();
  98412. for (var i = 0; i < 10; ++i) {
  98413. m.data[i] = this.data[i] + matrix.data[i];
  98414. }
  98415. return m;
  98416. };
  98417. QuadraticMatrix.FromData = function (a, b, c, d) {
  98418. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  98419. };
  98420. //returning an array to avoid garbage collection
  98421. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  98422. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  98423. };
  98424. return QuadraticMatrix;
  98425. }());
  98426. BABYLON.QuadraticMatrix = QuadraticMatrix;
  98427. var Reference = /** @class */ (function () {
  98428. function Reference(vertexId, triangleId) {
  98429. this.vertexId = vertexId;
  98430. this.triangleId = triangleId;
  98431. }
  98432. return Reference;
  98433. }());
  98434. BABYLON.Reference = Reference;
  98435. /**
  98436. * An implementation of the Quadratic Error simplification algorithm.
  98437. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  98438. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  98439. * @author RaananW
  98440. */
  98441. var QuadraticErrorSimplification = /** @class */ (function () {
  98442. function QuadraticErrorSimplification(_mesh) {
  98443. this._mesh = _mesh;
  98444. this.syncIterations = 5000;
  98445. this.aggressiveness = 7;
  98446. this.decimationIterations = 100;
  98447. this.boundingBoxEpsilon = BABYLON.Epsilon;
  98448. }
  98449. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  98450. var _this = this;
  98451. this.initDecimatedMesh();
  98452. //iterating through the submeshes array, one after the other.
  98453. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  98454. _this.initWithMesh(loop.index, function () {
  98455. _this.runDecimation(settings, loop.index, function () {
  98456. loop.executeNext();
  98457. });
  98458. }, settings.optimizeMesh);
  98459. }, function () {
  98460. setTimeout(function () {
  98461. successCallback(_this._reconstructedMesh);
  98462. }, 0);
  98463. });
  98464. };
  98465. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  98466. var _this = this;
  98467. var targetCount = ~~(this.triangles.length * settings.quality);
  98468. var deletedTriangles = 0;
  98469. var triangleCount = this.triangles.length;
  98470. var iterationFunction = function (iteration, callback) {
  98471. setTimeout(function () {
  98472. if (iteration % 5 === 0) {
  98473. _this.updateMesh(iteration === 0);
  98474. }
  98475. for (var i = 0; i < _this.triangles.length; ++i) {
  98476. _this.triangles[i].isDirty = false;
  98477. }
  98478. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  98479. var trianglesIterator = function (i) {
  98480. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  98481. var t = _this.triangles[tIdx];
  98482. if (!t)
  98483. return;
  98484. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  98485. return;
  98486. }
  98487. for (var j = 0; j < 3; ++j) {
  98488. if (t.error[j] < threshold) {
  98489. var deleted0 = [];
  98490. var deleted1 = [];
  98491. var v0 = t.vertices[j];
  98492. var v1 = t.vertices[(j + 1) % 3];
  98493. if (v0.isBorder || v1.isBorder)
  98494. continue;
  98495. var p = BABYLON.Vector3.Zero();
  98496. var n = BABYLON.Vector3.Zero();
  98497. var uv = BABYLON.Vector2.Zero();
  98498. var color = new BABYLON.Color4(0, 0, 0, 1);
  98499. _this.calculateError(v0, v1, p, n, uv, color);
  98500. var delTr = new Array();
  98501. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  98502. continue;
  98503. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  98504. continue;
  98505. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  98506. continue;
  98507. var uniqueArray = new Array();
  98508. delTr.forEach(function (deletedT) {
  98509. if (uniqueArray.indexOf(deletedT) === -1) {
  98510. deletedT.deletePending = true;
  98511. uniqueArray.push(deletedT);
  98512. }
  98513. });
  98514. if (uniqueArray.length % 2 !== 0) {
  98515. continue;
  98516. }
  98517. v0.q = v1.q.add(v0.q);
  98518. v0.updatePosition(p);
  98519. var tStart = _this.references.length;
  98520. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  98521. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  98522. var tCount = _this.references.length - tStart;
  98523. if (tCount <= v0.triangleCount) {
  98524. if (tCount) {
  98525. for (var c = 0; c < tCount; c++) {
  98526. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  98527. }
  98528. }
  98529. }
  98530. else {
  98531. v0.triangleStart = tStart;
  98532. }
  98533. v0.triangleCount = tCount;
  98534. break;
  98535. }
  98536. }
  98537. };
  98538. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  98539. }, 0);
  98540. };
  98541. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  98542. if (triangleCount - deletedTriangles <= targetCount)
  98543. loop.breakLoop();
  98544. else {
  98545. iterationFunction(loop.index, function () {
  98546. loop.executeNext();
  98547. });
  98548. }
  98549. }, function () {
  98550. setTimeout(function () {
  98551. //reconstruct this part of the mesh
  98552. _this.reconstructMesh(submeshIndex);
  98553. successCallback();
  98554. }, 0);
  98555. });
  98556. };
  98557. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  98558. var _this = this;
  98559. this.vertices = [];
  98560. this.triangles = [];
  98561. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  98562. var indices = this._mesh.getIndices();
  98563. var submesh = this._mesh.subMeshes[submeshIndex];
  98564. var findInVertices = function (positionToSearch) {
  98565. if (optimizeMesh) {
  98566. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  98567. if (_this.vertices[ii].position.equals(positionToSearch)) {
  98568. return _this.vertices[ii];
  98569. }
  98570. }
  98571. }
  98572. return null;
  98573. };
  98574. var vertexReferences = [];
  98575. var vertexInit = function (i) {
  98576. if (!positionData) {
  98577. return;
  98578. }
  98579. var offset = i + submesh.verticesStart;
  98580. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  98581. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  98582. vertex.originalOffsets.push(offset);
  98583. if (vertex.id === _this.vertices.length) {
  98584. _this.vertices.push(vertex);
  98585. }
  98586. vertexReferences.push(vertex.id);
  98587. };
  98588. //var totalVertices = mesh.getTotalVertices();
  98589. var totalVertices = submesh.verticesCount;
  98590. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  98591. var indicesInit = function (i) {
  98592. if (!indices) {
  98593. return;
  98594. }
  98595. var offset = (submesh.indexStart / 3) + i;
  98596. var pos = (offset * 3);
  98597. var i0 = indices[pos + 0];
  98598. var i1 = indices[pos + 1];
  98599. var i2 = indices[pos + 2];
  98600. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  98601. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  98602. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  98603. var triangle = new DecimationTriangle([v0, v1, v2]);
  98604. triangle.originalOffset = pos;
  98605. _this.triangles.push(triangle);
  98606. };
  98607. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  98608. _this.init(callback);
  98609. });
  98610. });
  98611. };
  98612. QuadraticErrorSimplification.prototype.init = function (callback) {
  98613. var _this = this;
  98614. var triangleInit1 = function (i) {
  98615. var t = _this.triangles[i];
  98616. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  98617. for (var j = 0; j < 3; j++) {
  98618. 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))));
  98619. }
  98620. };
  98621. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  98622. var triangleInit2 = function (i) {
  98623. var t = _this.triangles[i];
  98624. for (var j = 0; j < 3; ++j) {
  98625. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  98626. }
  98627. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98628. };
  98629. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  98630. callback();
  98631. });
  98632. });
  98633. };
  98634. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  98635. var newTriangles = [];
  98636. var i;
  98637. for (i = 0; i < this.vertices.length; ++i) {
  98638. this.vertices[i].triangleCount = 0;
  98639. }
  98640. var t;
  98641. var j;
  98642. for (i = 0; i < this.triangles.length; ++i) {
  98643. if (!this.triangles[i].deleted) {
  98644. t = this.triangles[i];
  98645. for (j = 0; j < 3; ++j) {
  98646. t.vertices[j].triangleCount = 1;
  98647. }
  98648. newTriangles.push(t);
  98649. }
  98650. }
  98651. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  98652. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  98653. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  98654. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  98655. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  98656. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  98657. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  98658. var vertexCount = 0;
  98659. for (i = 0; i < this.vertices.length; ++i) {
  98660. var vertex = this.vertices[i];
  98661. vertex.id = vertexCount;
  98662. if (vertex.triangleCount) {
  98663. vertex.originalOffsets.forEach(function (originalOffset) {
  98664. if (!normalData) {
  98665. return;
  98666. }
  98667. newPositionData.push(vertex.position.x);
  98668. newPositionData.push(vertex.position.y);
  98669. newPositionData.push(vertex.position.z);
  98670. newNormalData.push(normalData[originalOffset * 3]);
  98671. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  98672. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  98673. if (uvs && uvs.length) {
  98674. newUVsData.push(uvs[(originalOffset * 2)]);
  98675. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  98676. }
  98677. else if (colorsData && colorsData.length) {
  98678. newColorsData.push(colorsData[(originalOffset * 4)]);
  98679. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  98680. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  98681. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  98682. }
  98683. ++vertexCount;
  98684. });
  98685. }
  98686. }
  98687. var startingIndex = this._reconstructedMesh.getTotalIndices();
  98688. var startingVertex = this._reconstructedMesh.getTotalVertices();
  98689. var submeshesArray = this._reconstructedMesh.subMeshes;
  98690. this._reconstructedMesh.subMeshes = [];
  98691. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  98692. var originalIndices = this._mesh.getIndices();
  98693. for (i = 0; i < newTriangles.length; ++i) {
  98694. t = newTriangles[i]; //now get the new referencing point for each vertex
  98695. [0, 1, 2].forEach(function (idx) {
  98696. var id = originalIndices[t.originalOffset + idx];
  98697. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  98698. if (offset < 0)
  98699. offset = 0;
  98700. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  98701. });
  98702. }
  98703. //overwriting the old vertex buffers and indices.
  98704. this._reconstructedMesh.setIndices(newIndicesArray);
  98705. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  98706. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  98707. if (newUVsData.length > 0)
  98708. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  98709. if (newColorsData.length > 0)
  98710. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  98711. //create submesh
  98712. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  98713. if (submeshIndex > 0) {
  98714. this._reconstructedMesh.subMeshes = [];
  98715. submeshesArray.forEach(function (submesh) {
  98716. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  98717. });
  98718. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  98719. }
  98720. };
  98721. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98722. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98723. this._reconstructedMesh.material = this._mesh.material;
  98724. this._reconstructedMesh.parent = this._mesh.parent;
  98725. this._reconstructedMesh.isVisible = false;
  98726. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98727. };
  98728. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98729. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98730. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98731. if (t.deleted)
  98732. continue;
  98733. var s = this.references[vertex1.triangleStart + i].vertexId;
  98734. var v1 = t.vertices[(s + 1) % 3];
  98735. var v2 = t.vertices[(s + 2) % 3];
  98736. if ((v1 === vertex2 || v2 === vertex2)) {
  98737. deletedArray[i] = true;
  98738. delTr.push(t);
  98739. continue;
  98740. }
  98741. var d1 = v1.position.subtract(point);
  98742. d1 = d1.normalize();
  98743. var d2 = v2.position.subtract(point);
  98744. d2 = d2.normalize();
  98745. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98746. return true;
  98747. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98748. deletedArray[i] = false;
  98749. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98750. return true;
  98751. }
  98752. return false;
  98753. };
  98754. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98755. var newDeleted = deletedTriangles;
  98756. for (var i = 0; i < vertex.triangleCount; ++i) {
  98757. var ref = this.references[vertex.triangleStart + i];
  98758. var t = this.triangles[ref.triangleId];
  98759. if (t.deleted)
  98760. continue;
  98761. if (deletedArray[i] && t.deletePending) {
  98762. t.deleted = true;
  98763. newDeleted++;
  98764. continue;
  98765. }
  98766. t.vertices[ref.vertexId] = origVertex;
  98767. t.isDirty = true;
  98768. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98769. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98770. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98771. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98772. this.references.push(ref);
  98773. }
  98774. return newDeleted;
  98775. };
  98776. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  98777. for (var i = 0; i < this.vertices.length; ++i) {
  98778. var vCount = [];
  98779. var vId = [];
  98780. var v = this.vertices[i];
  98781. var j;
  98782. for (j = 0; j < v.triangleCount; ++j) {
  98783. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  98784. for (var ii = 0; ii < 3; ii++) {
  98785. var ofs = 0;
  98786. var vv = triangle.vertices[ii];
  98787. while (ofs < vCount.length) {
  98788. if (vId[ofs] === vv.id)
  98789. break;
  98790. ++ofs;
  98791. }
  98792. if (ofs === vCount.length) {
  98793. vCount.push(1);
  98794. vId.push(vv.id);
  98795. }
  98796. else {
  98797. vCount[ofs]++;
  98798. }
  98799. }
  98800. }
  98801. for (j = 0; j < vCount.length; ++j) {
  98802. if (vCount[j] === 1) {
  98803. this.vertices[vId[j]].isBorder = true;
  98804. }
  98805. else {
  98806. this.vertices[vId[j]].isBorder = false;
  98807. }
  98808. }
  98809. }
  98810. };
  98811. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  98812. if (identifyBorders === void 0) { identifyBorders = false; }
  98813. var i;
  98814. if (!identifyBorders) {
  98815. var newTrianglesVector = [];
  98816. for (i = 0; i < this.triangles.length; ++i) {
  98817. if (!this.triangles[i].deleted) {
  98818. newTrianglesVector.push(this.triangles[i]);
  98819. }
  98820. }
  98821. this.triangles = newTrianglesVector;
  98822. }
  98823. for (i = 0; i < this.vertices.length; ++i) {
  98824. this.vertices[i].triangleCount = 0;
  98825. this.vertices[i].triangleStart = 0;
  98826. }
  98827. var t;
  98828. var j;
  98829. var v;
  98830. for (i = 0; i < this.triangles.length; ++i) {
  98831. t = this.triangles[i];
  98832. for (j = 0; j < 3; ++j) {
  98833. v = t.vertices[j];
  98834. v.triangleCount++;
  98835. }
  98836. }
  98837. var tStart = 0;
  98838. for (i = 0; i < this.vertices.length; ++i) {
  98839. this.vertices[i].triangleStart = tStart;
  98840. tStart += this.vertices[i].triangleCount;
  98841. this.vertices[i].triangleCount = 0;
  98842. }
  98843. var newReferences = new Array(this.triangles.length * 3);
  98844. for (i = 0; i < this.triangles.length; ++i) {
  98845. t = this.triangles[i];
  98846. for (j = 0; j < 3; ++j) {
  98847. v = t.vertices[j];
  98848. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  98849. v.triangleCount++;
  98850. }
  98851. }
  98852. this.references = newReferences;
  98853. if (identifyBorders) {
  98854. this.identifyBorder();
  98855. }
  98856. };
  98857. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  98858. var x = point.x;
  98859. var y = point.y;
  98860. var z = point.z;
  98861. 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
  98862. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  98863. };
  98864. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  98865. var q = vertex1.q.add(vertex2.q);
  98866. var border = vertex1.isBorder && vertex2.isBorder;
  98867. var error = 0;
  98868. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  98869. if (qDet !== 0 && !border) {
  98870. if (!pointResult) {
  98871. pointResult = BABYLON.Vector3.Zero();
  98872. }
  98873. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  98874. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  98875. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  98876. error = this.vertexError(q, pointResult);
  98877. }
  98878. else {
  98879. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  98880. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  98881. var error1 = this.vertexError(q, vertex1.position);
  98882. var error2 = this.vertexError(q, vertex2.position);
  98883. var error3 = this.vertexError(q, p3);
  98884. error = Math.min(error1, error2, error3);
  98885. if (error === error1) {
  98886. if (pointResult) {
  98887. pointResult.copyFrom(vertex1.position);
  98888. }
  98889. }
  98890. else if (error === error2) {
  98891. if (pointResult) {
  98892. pointResult.copyFrom(vertex2.position);
  98893. }
  98894. }
  98895. else {
  98896. if (pointResult) {
  98897. pointResult.copyFrom(p3);
  98898. }
  98899. }
  98900. }
  98901. return error;
  98902. };
  98903. return QuadraticErrorSimplification;
  98904. }());
  98905. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  98906. })(BABYLON || (BABYLON = {}));
  98907. //# sourceMappingURL=babylon.meshSimplification.js.map
  98908. var BABYLON;
  98909. (function (BABYLON) {
  98910. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  98911. get: function () {
  98912. if (!this._simplificationQueue) {
  98913. this._simplificationQueue = new BABYLON.SimplificationQueue();
  98914. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  98915. if (!component) {
  98916. component = new SimplicationQueueSceneComponent(this);
  98917. this._addComponent(component);
  98918. }
  98919. }
  98920. return this._simplificationQueue;
  98921. },
  98922. set: function (value) {
  98923. this._simplificationQueue = value;
  98924. },
  98925. enumerable: true,
  98926. configurable: true
  98927. });
  98928. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  98929. if (parallelProcessing === void 0) { parallelProcessing = true; }
  98930. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  98931. this.getScene().simplificationQueue.addTask({
  98932. settings: settings,
  98933. parallelProcessing: parallelProcessing,
  98934. mesh: this,
  98935. simplificationType: simplificationType,
  98936. successCallback: successCallback
  98937. });
  98938. return this;
  98939. };
  98940. /**
  98941. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  98942. * created in a scene
  98943. */
  98944. var SimplicationQueueSceneComponent = /** @class */ (function () {
  98945. /**
  98946. * Creates a new instance of the component for the given scene
  98947. * @param scene Defines the scene to register the component in
  98948. */
  98949. function SimplicationQueueSceneComponent(scene) {
  98950. /**
  98951. * The component name helpfull to identify the component in the list of scene components.
  98952. */
  98953. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  98954. this.scene = scene;
  98955. }
  98956. /**
  98957. * Registers the component in a given scene
  98958. */
  98959. SimplicationQueueSceneComponent.prototype.register = function () {
  98960. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  98961. };
  98962. /**
  98963. * Rebuilds the elements related to this component in case of
  98964. * context lost for instance.
  98965. */
  98966. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  98967. // Nothing to do for this component
  98968. };
  98969. /**
  98970. * Disposes the component and the associated ressources
  98971. */
  98972. SimplicationQueueSceneComponent.prototype.dispose = function () {
  98973. // Nothing to do for this component
  98974. };
  98975. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  98976. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  98977. this.scene._simplificationQueue.executeNext();
  98978. }
  98979. };
  98980. return SimplicationQueueSceneComponent;
  98981. }());
  98982. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  98983. })(BABYLON || (BABYLON = {}));
  98984. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  98985. var BABYLON;
  98986. (function (BABYLON) {
  98987. var MeshLODLevel = /** @class */ (function () {
  98988. function MeshLODLevel(distance, mesh) {
  98989. this.distance = distance;
  98990. this.mesh = mesh;
  98991. }
  98992. return MeshLODLevel;
  98993. }());
  98994. BABYLON.MeshLODLevel = MeshLODLevel;
  98995. })(BABYLON || (BABYLON = {}));
  98996. //# sourceMappingURL=babylon.meshLODLevel.js.map
  98997. var BABYLON;
  98998. (function (BABYLON) {
  98999. /**
  99000. * Defines the root class used to create scene optimization to use with SceneOptimizer
  99001. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99002. */
  99003. var SceneOptimization = /** @class */ (function () {
  99004. /**
  99005. * Creates the SceneOptimization object
  99006. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99007. * @param desc defines the description associated with the optimization
  99008. */
  99009. function SceneOptimization(
  99010. /**
  99011. * Defines the priority of this optimization (0 by default which means first in the list)
  99012. */
  99013. priority) {
  99014. if (priority === void 0) { priority = 0; }
  99015. this.priority = priority;
  99016. }
  99017. /**
  99018. * Gets a string describing the action executed by the current optimization
  99019. * @returns description string
  99020. */
  99021. SceneOptimization.prototype.getDescription = function () {
  99022. return "";
  99023. };
  99024. /**
  99025. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99026. * @param scene defines the current scene where to apply this optimization
  99027. * @param optimizer defines the current optimizer
  99028. * @returns true if everything that can be done was applied
  99029. */
  99030. SceneOptimization.prototype.apply = function (scene, optimizer) {
  99031. return true;
  99032. };
  99033. ;
  99034. return SceneOptimization;
  99035. }());
  99036. BABYLON.SceneOptimization = SceneOptimization;
  99037. /**
  99038. * Defines an optimization used to reduce the size of render target textures
  99039. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99040. */
  99041. var TextureOptimization = /** @class */ (function (_super) {
  99042. __extends(TextureOptimization, _super);
  99043. /**
  99044. * Creates the TextureOptimization object
  99045. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99046. * @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
  99047. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99048. */
  99049. function TextureOptimization(
  99050. /**
  99051. * Defines the priority of this optimization (0 by default which means first in the list)
  99052. */
  99053. priority,
  99054. /**
  99055. * 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
  99056. */
  99057. maximumSize,
  99058. /**
  99059. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99060. */
  99061. step) {
  99062. if (priority === void 0) { priority = 0; }
  99063. if (maximumSize === void 0) { maximumSize = 1024; }
  99064. if (step === void 0) { step = 0.5; }
  99065. var _this = _super.call(this, priority) || this;
  99066. _this.priority = priority;
  99067. _this.maximumSize = maximumSize;
  99068. _this.step = step;
  99069. return _this;
  99070. }
  99071. /**
  99072. * Gets a string describing the action executed by the current optimization
  99073. * @returns description string
  99074. */
  99075. TextureOptimization.prototype.getDescription = function () {
  99076. return "Reducing render target texture size to " + this.maximumSize;
  99077. };
  99078. /**
  99079. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99080. * @param scene defines the current scene where to apply this optimization
  99081. * @param optimizer defines the current optimizer
  99082. * @returns true if everything that can be done was applied
  99083. */
  99084. TextureOptimization.prototype.apply = function (scene, optimizer) {
  99085. var allDone = true;
  99086. for (var index = 0; index < scene.textures.length; index++) {
  99087. var texture = scene.textures[index];
  99088. if (!texture.canRescale || texture.getContext) {
  99089. continue;
  99090. }
  99091. var currentSize = texture.getSize();
  99092. var maxDimension = Math.max(currentSize.width, currentSize.height);
  99093. if (maxDimension > this.maximumSize) {
  99094. texture.scale(this.step);
  99095. allDone = false;
  99096. }
  99097. }
  99098. return allDone;
  99099. };
  99100. return TextureOptimization;
  99101. }(SceneOptimization));
  99102. BABYLON.TextureOptimization = TextureOptimization;
  99103. /**
  99104. * Defines an optimization used to increase or decrease the rendering resolution
  99105. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99106. */
  99107. var HardwareScalingOptimization = /** @class */ (function (_super) {
  99108. __extends(HardwareScalingOptimization, _super);
  99109. /**
  99110. * Creates the HardwareScalingOptimization object
  99111. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99112. * @param maximumScale defines the maximum scale to use (2 by default)
  99113. * @param step defines the step to use between two passes (0.5 by default)
  99114. */
  99115. function HardwareScalingOptimization(
  99116. /**
  99117. * Defines the priority of this optimization (0 by default which means first in the list)
  99118. */
  99119. priority,
  99120. /**
  99121. * Defines the maximum scale to use (2 by default)
  99122. */
  99123. maximumScale,
  99124. /**
  99125. * Defines the step to use between two passes (0.5 by default)
  99126. */
  99127. step) {
  99128. if (priority === void 0) { priority = 0; }
  99129. if (maximumScale === void 0) { maximumScale = 2; }
  99130. if (step === void 0) { step = 0.25; }
  99131. var _this = _super.call(this, priority) || this;
  99132. _this.priority = priority;
  99133. _this.maximumScale = maximumScale;
  99134. _this.step = step;
  99135. _this._currentScale = -1;
  99136. _this._directionOffset = 1;
  99137. return _this;
  99138. }
  99139. /**
  99140. * Gets a string describing the action executed by the current optimization
  99141. * @return description string
  99142. */
  99143. HardwareScalingOptimization.prototype.getDescription = function () {
  99144. return "Setting hardware scaling level to " + this._currentScale;
  99145. };
  99146. /**
  99147. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99148. * @param scene defines the current scene where to apply this optimization
  99149. * @param optimizer defines the current optimizer
  99150. * @returns true if everything that can be done was applied
  99151. */
  99152. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  99153. if (this._currentScale === -1) {
  99154. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  99155. if (this._currentScale > this.maximumScale) {
  99156. this._directionOffset = -1;
  99157. }
  99158. }
  99159. this._currentScale += this._directionOffset * this.step;
  99160. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  99161. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  99162. };
  99163. ;
  99164. return HardwareScalingOptimization;
  99165. }(SceneOptimization));
  99166. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  99167. /**
  99168. * Defines an optimization used to remove shadows
  99169. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99170. */
  99171. var ShadowsOptimization = /** @class */ (function (_super) {
  99172. __extends(ShadowsOptimization, _super);
  99173. function ShadowsOptimization() {
  99174. return _super !== null && _super.apply(this, arguments) || this;
  99175. }
  99176. /**
  99177. * Gets a string describing the action executed by the current optimization
  99178. * @return description string
  99179. */
  99180. ShadowsOptimization.prototype.getDescription = function () {
  99181. return "Turning shadows on/off";
  99182. };
  99183. /**
  99184. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99185. * @param scene defines the current scene where to apply this optimization
  99186. * @param optimizer defines the current optimizer
  99187. * @returns true if everything that can be done was applied
  99188. */
  99189. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  99190. scene.shadowsEnabled = optimizer.isInImprovementMode;
  99191. return true;
  99192. };
  99193. ;
  99194. return ShadowsOptimization;
  99195. }(SceneOptimization));
  99196. BABYLON.ShadowsOptimization = ShadowsOptimization;
  99197. /**
  99198. * Defines an optimization used to turn post-processes off
  99199. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99200. */
  99201. var PostProcessesOptimization = /** @class */ (function (_super) {
  99202. __extends(PostProcessesOptimization, _super);
  99203. function PostProcessesOptimization() {
  99204. return _super !== null && _super.apply(this, arguments) || this;
  99205. }
  99206. /**
  99207. * Gets a string describing the action executed by the current optimization
  99208. * @return description string
  99209. */
  99210. PostProcessesOptimization.prototype.getDescription = function () {
  99211. return "Turning post-processes on/off";
  99212. };
  99213. /**
  99214. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99215. * @param scene defines the current scene where to apply this optimization
  99216. * @param optimizer defines the current optimizer
  99217. * @returns true if everything that can be done was applied
  99218. */
  99219. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  99220. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  99221. return true;
  99222. };
  99223. ;
  99224. return PostProcessesOptimization;
  99225. }(SceneOptimization));
  99226. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  99227. /**
  99228. * Defines an optimization used to turn lens flares off
  99229. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99230. */
  99231. var LensFlaresOptimization = /** @class */ (function (_super) {
  99232. __extends(LensFlaresOptimization, _super);
  99233. function LensFlaresOptimization() {
  99234. return _super !== null && _super.apply(this, arguments) || this;
  99235. }
  99236. /**
  99237. * Gets a string describing the action executed by the current optimization
  99238. * @return description string
  99239. */
  99240. LensFlaresOptimization.prototype.getDescription = function () {
  99241. return "Turning lens flares on/off";
  99242. };
  99243. /**
  99244. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99245. * @param scene defines the current scene where to apply this optimization
  99246. * @param optimizer defines the current optimizer
  99247. * @returns true if everything that can be done was applied
  99248. */
  99249. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  99250. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  99251. return true;
  99252. };
  99253. ;
  99254. return LensFlaresOptimization;
  99255. }(SceneOptimization));
  99256. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  99257. /**
  99258. * Defines an optimization based on user defined callback.
  99259. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99260. */
  99261. var CustomOptimization = /** @class */ (function (_super) {
  99262. __extends(CustomOptimization, _super);
  99263. function CustomOptimization() {
  99264. return _super !== null && _super.apply(this, arguments) || this;
  99265. }
  99266. /**
  99267. * Gets a string describing the action executed by the current optimization
  99268. * @returns description string
  99269. */
  99270. CustomOptimization.prototype.getDescription = function () {
  99271. if (this.onGetDescription) {
  99272. return this.onGetDescription();
  99273. }
  99274. return "Running user defined callback";
  99275. };
  99276. /**
  99277. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99278. * @param scene defines the current scene where to apply this optimization
  99279. * @param optimizer defines the current optimizer
  99280. * @returns true if everything that can be done was applied
  99281. */
  99282. CustomOptimization.prototype.apply = function (scene, optimizer) {
  99283. if (this.onApply) {
  99284. return this.onApply(scene, optimizer);
  99285. }
  99286. return true;
  99287. };
  99288. ;
  99289. return CustomOptimization;
  99290. }(SceneOptimization));
  99291. BABYLON.CustomOptimization = CustomOptimization;
  99292. /**
  99293. * Defines an optimization used to turn particles off
  99294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99295. */
  99296. var ParticlesOptimization = /** @class */ (function (_super) {
  99297. __extends(ParticlesOptimization, _super);
  99298. function ParticlesOptimization() {
  99299. return _super !== null && _super.apply(this, arguments) || this;
  99300. }
  99301. /**
  99302. * Gets a string describing the action executed by the current optimization
  99303. * @return description string
  99304. */
  99305. ParticlesOptimization.prototype.getDescription = function () {
  99306. return "Turning particles on/off";
  99307. };
  99308. /**
  99309. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99310. * @param scene defines the current scene where to apply this optimization
  99311. * @param optimizer defines the current optimizer
  99312. * @returns true if everything that can be done was applied
  99313. */
  99314. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  99315. scene.particlesEnabled = optimizer.isInImprovementMode;
  99316. return true;
  99317. };
  99318. ;
  99319. return ParticlesOptimization;
  99320. }(SceneOptimization));
  99321. BABYLON.ParticlesOptimization = ParticlesOptimization;
  99322. /**
  99323. * Defines an optimization used to turn render targets off
  99324. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99325. */
  99326. var RenderTargetsOptimization = /** @class */ (function (_super) {
  99327. __extends(RenderTargetsOptimization, _super);
  99328. function RenderTargetsOptimization() {
  99329. return _super !== null && _super.apply(this, arguments) || this;
  99330. }
  99331. /**
  99332. * Gets a string describing the action executed by the current optimization
  99333. * @return description string
  99334. */
  99335. RenderTargetsOptimization.prototype.getDescription = function () {
  99336. return "Turning render targets off";
  99337. };
  99338. /**
  99339. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99340. * @param scene defines the current scene where to apply this optimization
  99341. * @param optimizer defines the current optimizer
  99342. * @returns true if everything that can be done was applied
  99343. */
  99344. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  99345. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  99346. return true;
  99347. };
  99348. ;
  99349. return RenderTargetsOptimization;
  99350. }(SceneOptimization));
  99351. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  99352. /**
  99353. * Defines an optimization used to merge meshes with compatible materials
  99354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99355. */
  99356. var MergeMeshesOptimization = /** @class */ (function (_super) {
  99357. __extends(MergeMeshesOptimization, _super);
  99358. function MergeMeshesOptimization() {
  99359. var _this = _super !== null && _super.apply(this, arguments) || this;
  99360. _this._canBeMerged = function (abstractMesh) {
  99361. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  99362. return false;
  99363. }
  99364. var mesh = abstractMesh;
  99365. if (mesh.isDisposed()) {
  99366. return false;
  99367. }
  99368. if (!mesh.isVisible || !mesh.isEnabled()) {
  99369. return false;
  99370. }
  99371. if (mesh.instances.length > 0) {
  99372. return false;
  99373. }
  99374. if (mesh.skeleton || mesh.hasLODLevels) {
  99375. return false;
  99376. }
  99377. return true;
  99378. };
  99379. return _this;
  99380. }
  99381. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  99382. /**
  99383. * Gets or sets a boolean which defines if optimization octree has to be updated
  99384. */
  99385. get: function () {
  99386. return MergeMeshesOptimization._UpdateSelectionTree;
  99387. },
  99388. /**
  99389. * Gets or sets a boolean which defines if optimization octree has to be updated
  99390. */
  99391. set: function (value) {
  99392. MergeMeshesOptimization._UpdateSelectionTree = value;
  99393. },
  99394. enumerable: true,
  99395. configurable: true
  99396. });
  99397. /**
  99398. * Gets a string describing the action executed by the current optimization
  99399. * @return description string
  99400. */
  99401. MergeMeshesOptimization.prototype.getDescription = function () {
  99402. return "Merging similar meshes together";
  99403. };
  99404. /**
  99405. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99406. * @param scene defines the current scene where to apply this optimization
  99407. * @param optimizer defines the current optimizer
  99408. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  99409. * @returns true if everything that can be done was applied
  99410. */
  99411. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  99412. var globalPool = scene.meshes.slice(0);
  99413. var globalLength = globalPool.length;
  99414. for (var index = 0; index < globalLength; index++) {
  99415. var currentPool = new Array();
  99416. var current = globalPool[index];
  99417. // Checks
  99418. if (!this._canBeMerged(current)) {
  99419. continue;
  99420. }
  99421. currentPool.push(current);
  99422. // Find compatible meshes
  99423. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  99424. var otherMesh = globalPool[subIndex];
  99425. if (!this._canBeMerged(otherMesh)) {
  99426. continue;
  99427. }
  99428. if (otherMesh.material !== current.material) {
  99429. continue;
  99430. }
  99431. if (otherMesh.checkCollisions !== current.checkCollisions) {
  99432. continue;
  99433. }
  99434. currentPool.push(otherMesh);
  99435. globalLength--;
  99436. globalPool.splice(subIndex, 1);
  99437. subIndex--;
  99438. }
  99439. if (currentPool.length < 2) {
  99440. continue;
  99441. }
  99442. // Merge meshes
  99443. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  99444. }
  99445. if (updateSelectionTree != undefined) {
  99446. if (updateSelectionTree) {
  99447. scene.createOrUpdateSelectionOctree();
  99448. }
  99449. }
  99450. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  99451. scene.createOrUpdateSelectionOctree();
  99452. }
  99453. return true;
  99454. };
  99455. ;
  99456. MergeMeshesOptimization._UpdateSelectionTree = false;
  99457. return MergeMeshesOptimization;
  99458. }(SceneOptimization));
  99459. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  99460. /**
  99461. * Defines a list of options used by SceneOptimizer
  99462. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99463. */
  99464. var SceneOptimizerOptions = /** @class */ (function () {
  99465. /**
  99466. * Creates a new list of options used by SceneOptimizer
  99467. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  99468. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  99469. */
  99470. function SceneOptimizerOptions(
  99471. /**
  99472. * Defines the target frame rate to reach (60 by default)
  99473. */
  99474. targetFrameRate,
  99475. /**
  99476. * Defines the interval between two checkes (2000ms by default)
  99477. */
  99478. trackerDuration) {
  99479. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  99480. if (trackerDuration === void 0) { trackerDuration = 2000; }
  99481. this.targetFrameRate = targetFrameRate;
  99482. this.trackerDuration = trackerDuration;
  99483. /**
  99484. * Gets the list of optimizations to apply
  99485. */
  99486. this.optimizations = new Array();
  99487. }
  99488. /**
  99489. * Add a new optimization
  99490. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  99491. * @returns the current SceneOptimizerOptions
  99492. */
  99493. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  99494. this.optimizations.push(optimization);
  99495. return this;
  99496. };
  99497. /**
  99498. * Add a new custom optimization
  99499. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  99500. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  99501. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99502. * @returns the current SceneOptimizerOptions
  99503. */
  99504. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  99505. if (priority === void 0) { priority = 0; }
  99506. var optimization = new CustomOptimization(priority);
  99507. optimization.onApply = onApply;
  99508. optimization.onGetDescription = onGetDescription;
  99509. this.optimizations.push(optimization);
  99510. return this;
  99511. };
  99512. /**
  99513. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  99514. * @param targetFrameRate defines the target frame rate (60 by default)
  99515. * @returns a SceneOptimizerOptions object
  99516. */
  99517. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  99518. var result = new SceneOptimizerOptions(targetFrameRate);
  99519. var priority = 0;
  99520. result.addOptimization(new MergeMeshesOptimization(priority));
  99521. result.addOptimization(new ShadowsOptimization(priority));
  99522. result.addOptimization(new LensFlaresOptimization(priority));
  99523. // Next priority
  99524. priority++;
  99525. result.addOptimization(new PostProcessesOptimization(priority));
  99526. result.addOptimization(new ParticlesOptimization(priority));
  99527. // Next priority
  99528. priority++;
  99529. result.addOptimization(new TextureOptimization(priority, 1024));
  99530. return result;
  99531. };
  99532. /**
  99533. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  99534. * @param targetFrameRate defines the target frame rate (60 by default)
  99535. * @returns a SceneOptimizerOptions object
  99536. */
  99537. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  99538. var result = new SceneOptimizerOptions(targetFrameRate);
  99539. var priority = 0;
  99540. result.addOptimization(new MergeMeshesOptimization(priority));
  99541. result.addOptimization(new ShadowsOptimization(priority));
  99542. result.addOptimization(new LensFlaresOptimization(priority));
  99543. // Next priority
  99544. priority++;
  99545. result.addOptimization(new PostProcessesOptimization(priority));
  99546. result.addOptimization(new ParticlesOptimization(priority));
  99547. // Next priority
  99548. priority++;
  99549. result.addOptimization(new TextureOptimization(priority, 512));
  99550. // Next priority
  99551. priority++;
  99552. result.addOptimization(new RenderTargetsOptimization(priority));
  99553. // Next priority
  99554. priority++;
  99555. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  99556. return result;
  99557. };
  99558. /**
  99559. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  99560. * @param targetFrameRate defines the target frame rate (60 by default)
  99561. * @returns a SceneOptimizerOptions object
  99562. */
  99563. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  99564. var result = new SceneOptimizerOptions(targetFrameRate);
  99565. var priority = 0;
  99566. result.addOptimization(new MergeMeshesOptimization(priority));
  99567. result.addOptimization(new ShadowsOptimization(priority));
  99568. result.addOptimization(new LensFlaresOptimization(priority));
  99569. // Next priority
  99570. priority++;
  99571. result.addOptimization(new PostProcessesOptimization(priority));
  99572. result.addOptimization(new ParticlesOptimization(priority));
  99573. // Next priority
  99574. priority++;
  99575. result.addOptimization(new TextureOptimization(priority, 256));
  99576. // Next priority
  99577. priority++;
  99578. result.addOptimization(new RenderTargetsOptimization(priority));
  99579. // Next priority
  99580. priority++;
  99581. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  99582. return result;
  99583. };
  99584. return SceneOptimizerOptions;
  99585. }());
  99586. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  99587. /**
  99588. * Class used to run optimizations in order to reach a target frame rate
  99589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99590. */
  99591. var SceneOptimizer = /** @class */ (function () {
  99592. /**
  99593. * Creates a new SceneOptimizer
  99594. * @param scene defines the scene to work on
  99595. * @param options defines the options to use with the SceneOptimizer
  99596. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  99597. * @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)
  99598. */
  99599. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  99600. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  99601. if (improvementMode === void 0) { improvementMode = false; }
  99602. var _this = this;
  99603. this._isRunning = false;
  99604. this._currentPriorityLevel = 0;
  99605. this._targetFrameRate = 60;
  99606. this._trackerDuration = 2000;
  99607. this._currentFrameRate = 0;
  99608. this._improvementMode = false;
  99609. /**
  99610. * Defines an observable called when the optimizer reaches the target frame rate
  99611. */
  99612. this.onSuccessObservable = new BABYLON.Observable();
  99613. /**
  99614. * Defines an observable called when the optimizer enables an optimization
  99615. */
  99616. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  99617. /**
  99618. * Defines an observable called when the optimizer is not able to reach the target frame rate
  99619. */
  99620. this.onFailureObservable = new BABYLON.Observable();
  99621. if (!options) {
  99622. this._options = new SceneOptimizerOptions();
  99623. }
  99624. else {
  99625. this._options = options;
  99626. }
  99627. if (this._options.targetFrameRate) {
  99628. this._targetFrameRate = this._options.targetFrameRate;
  99629. }
  99630. if (this._options.trackerDuration) {
  99631. this._trackerDuration = this._options.trackerDuration;
  99632. }
  99633. if (autoGeneratePriorities) {
  99634. var priority = 0;
  99635. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  99636. var optim = _a[_i];
  99637. optim.priority = priority++;
  99638. }
  99639. }
  99640. this._improvementMode = improvementMode;
  99641. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99642. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  99643. _this._sceneDisposeObserver = null;
  99644. _this.dispose();
  99645. });
  99646. }
  99647. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  99648. /**
  99649. * Gets a boolean indicating if the optimizer is in improvement mode
  99650. */
  99651. get: function () {
  99652. return this._improvementMode;
  99653. },
  99654. enumerable: true,
  99655. configurable: true
  99656. });
  99657. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  99658. /**
  99659. * Gets the current priority level (0 at start)
  99660. */
  99661. get: function () {
  99662. return this._currentPriorityLevel;
  99663. },
  99664. enumerable: true,
  99665. configurable: true
  99666. });
  99667. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  99668. /**
  99669. * Gets the current frame rate checked by the SceneOptimizer
  99670. */
  99671. get: function () {
  99672. return this._currentFrameRate;
  99673. },
  99674. enumerable: true,
  99675. configurable: true
  99676. });
  99677. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  99678. /**
  99679. * Gets or sets the current target frame rate (60 by default)
  99680. */
  99681. get: function () {
  99682. return this._targetFrameRate;
  99683. },
  99684. /**
  99685. * Gets or sets the current target frame rate (60 by default)
  99686. */
  99687. set: function (value) {
  99688. this._targetFrameRate = value;
  99689. },
  99690. enumerable: true,
  99691. configurable: true
  99692. });
  99693. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  99694. /**
  99695. * Gets or sets the current interval between two checks (every 2000ms by default)
  99696. */
  99697. get: function () {
  99698. return this._trackerDuration;
  99699. },
  99700. /**
  99701. * Gets or sets the current interval between two checks (every 2000ms by default)
  99702. */
  99703. set: function (value) {
  99704. this._trackerDuration = value;
  99705. },
  99706. enumerable: true,
  99707. configurable: true
  99708. });
  99709. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  99710. /**
  99711. * Gets the list of active optimizations
  99712. */
  99713. get: function () {
  99714. return this._options.optimizations;
  99715. },
  99716. enumerable: true,
  99717. configurable: true
  99718. });
  99719. /**
  99720. * Stops the current optimizer
  99721. */
  99722. SceneOptimizer.prototype.stop = function () {
  99723. this._isRunning = false;
  99724. };
  99725. /**
  99726. * Reset the optimizer to initial step (current priority level = 0)
  99727. */
  99728. SceneOptimizer.prototype.reset = function () {
  99729. this._currentPriorityLevel = 0;
  99730. };
  99731. /**
  99732. * Start the optimizer. By default it will try to reach a specific framerate
  99733. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99734. */
  99735. SceneOptimizer.prototype.start = function () {
  99736. var _this = this;
  99737. if (this._isRunning) {
  99738. return;
  99739. }
  99740. this._isRunning = true;
  99741. // Let's wait for the scene to be ready before running our check
  99742. this._scene.executeWhenReady(function () {
  99743. setTimeout(function () {
  99744. _this._checkCurrentState();
  99745. }, _this._trackerDuration);
  99746. });
  99747. };
  99748. SceneOptimizer.prototype._checkCurrentState = function () {
  99749. var _this = this;
  99750. if (!this._isRunning) {
  99751. return;
  99752. }
  99753. var scene = this._scene;
  99754. var options = this._options;
  99755. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99756. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99757. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99758. this._isRunning = false;
  99759. this.onSuccessObservable.notifyObservers(this);
  99760. return;
  99761. }
  99762. // Apply current level of optimizations
  99763. var allDone = true;
  99764. var noOptimizationApplied = true;
  99765. for (var index = 0; index < options.optimizations.length; index++) {
  99766. var optimization = options.optimizations[index];
  99767. if (optimization.priority === this._currentPriorityLevel) {
  99768. noOptimizationApplied = false;
  99769. allDone = allDone && optimization.apply(scene, this);
  99770. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99771. }
  99772. }
  99773. // If no optimization was applied, this is a failure :(
  99774. if (noOptimizationApplied) {
  99775. this._isRunning = false;
  99776. this.onFailureObservable.notifyObservers(this);
  99777. return;
  99778. }
  99779. // If all optimizations were done, move to next level
  99780. if (allDone) {
  99781. this._currentPriorityLevel++;
  99782. }
  99783. // Let's the system running for a specific amount of time before checking FPS
  99784. scene.executeWhenReady(function () {
  99785. setTimeout(function () {
  99786. _this._checkCurrentState();
  99787. }, _this._trackerDuration);
  99788. });
  99789. };
  99790. /**
  99791. * Release all resources
  99792. */
  99793. SceneOptimizer.prototype.dispose = function () {
  99794. this.stop();
  99795. this.onSuccessObservable.clear();
  99796. this.onFailureObservable.clear();
  99797. this.onNewOptimizationAppliedObservable.clear();
  99798. if (this._sceneDisposeObserver) {
  99799. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99800. }
  99801. };
  99802. /**
  99803. * Helper function to create a SceneOptimizer with one single line of code
  99804. * @param scene defines the scene to work on
  99805. * @param options defines the options to use with the SceneOptimizer
  99806. * @param onSuccess defines a callback to call on success
  99807. * @param onFailure defines a callback to call on failure
  99808. * @returns the new SceneOptimizer object
  99809. */
  99810. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  99811. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  99812. if (onSuccess) {
  99813. optimizer.onSuccessObservable.add(function () {
  99814. onSuccess();
  99815. });
  99816. }
  99817. if (onFailure) {
  99818. optimizer.onFailureObservable.add(function () {
  99819. onFailure();
  99820. });
  99821. }
  99822. optimizer.start();
  99823. return optimizer;
  99824. };
  99825. return SceneOptimizer;
  99826. }());
  99827. BABYLON.SceneOptimizer = SceneOptimizer;
  99828. })(BABYLON || (BABYLON = {}));
  99829. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  99830. var BABYLON;
  99831. (function (BABYLON) {
  99832. /**
  99833. * Gets the outline renderer associated with the scene
  99834. * @returns a OutlineRenderer
  99835. */
  99836. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  99837. if (!this._outlineRenderer) {
  99838. this._outlineRenderer = new OutlineRenderer(this);
  99839. }
  99840. return this._outlineRenderer;
  99841. };
  99842. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  99843. get: function () {
  99844. return this._renderOutline;
  99845. },
  99846. set: function (value) {
  99847. if (value) {
  99848. // Lazy Load the component.
  99849. this.getScene().getOutlineRenderer();
  99850. }
  99851. this._renderOutline = value;
  99852. },
  99853. enumerable: true,
  99854. configurable: true
  99855. });
  99856. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  99857. get: function () {
  99858. return this._renderOverlay;
  99859. },
  99860. set: function (value) {
  99861. if (value) {
  99862. // Lazy Load the component.
  99863. this.getScene().getOutlineRenderer();
  99864. }
  99865. this._renderOverlay = value;
  99866. },
  99867. enumerable: true,
  99868. configurable: true
  99869. });
  99870. /**
  99871. * This class is responsible to draw bothe outline/overlay of meshes.
  99872. * It should not be used directly but through the available method on mesh.
  99873. */
  99874. var OutlineRenderer = /** @class */ (function () {
  99875. /**
  99876. * Instantiates a new outline renderer. (There could be only one per scene).
  99877. * @param scene Defines the scene it belongs to
  99878. */
  99879. function OutlineRenderer(scene) {
  99880. /**
  99881. * The name of the component. Each component must have a unique name.
  99882. */
  99883. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  99884. /**
  99885. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  99886. */
  99887. this.zOffset = 1;
  99888. this.scene = scene;
  99889. this._engine = scene.getEngine();
  99890. this.scene._addComponent(this);
  99891. }
  99892. /**
  99893. * Register the component to one instance of a scene.
  99894. */
  99895. OutlineRenderer.prototype.register = function () {
  99896. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  99897. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  99898. };
  99899. /**
  99900. * Rebuilds the elements related to this component in case of
  99901. * context lost for instance.
  99902. */
  99903. OutlineRenderer.prototype.rebuild = function () {
  99904. // Nothing to do here.
  99905. };
  99906. /**
  99907. * Disposes the component and the associated ressources.
  99908. */
  99909. OutlineRenderer.prototype.dispose = function () {
  99910. // Nothing to do here.
  99911. };
  99912. /**
  99913. * Renders the outline in the canvas.
  99914. * @param subMesh Defines the sumesh to render
  99915. * @param batch Defines the batch of meshes in case of instances
  99916. * @param useOverlay Defines if the rendering is for the overlay or the outline
  99917. */
  99918. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  99919. var _this = this;
  99920. if (useOverlay === void 0) { useOverlay = false; }
  99921. var scene = this.scene;
  99922. var engine = scene.getEngine();
  99923. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99924. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  99925. return;
  99926. }
  99927. var mesh = subMesh.getRenderingMesh();
  99928. var material = subMesh.getMaterial();
  99929. if (!material || !scene.activeCamera) {
  99930. return;
  99931. }
  99932. engine.enableEffect(this._effect);
  99933. // Logarithmic depth
  99934. if (material.useLogarithmicDepth) {
  99935. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  99936. }
  99937. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  99938. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  99939. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  99940. // Bones
  99941. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99942. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99943. }
  99944. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  99945. // Alpha test
  99946. if (material && material.needAlphaTesting()) {
  99947. var alphaTexture = material.getAlphaTestTexture();
  99948. if (alphaTexture) {
  99949. this._effect.setTexture("diffuseSampler", alphaTexture);
  99950. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  99951. }
  99952. }
  99953. engine.setZOffset(-this.zOffset);
  99954. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  99955. engine.setZOffset(0);
  99956. };
  99957. /**
  99958. * Returns whether or not the outline renderer is ready for a given submesh.
  99959. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  99960. * @param subMesh Defines the submesh to check readyness for
  99961. * @param useInstances Defines wheter wee are trying to render instances or not
  99962. * @returns true if ready otherwise false
  99963. */
  99964. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  99965. var defines = [];
  99966. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  99967. var mesh = subMesh.getMesh();
  99968. var material = subMesh.getMaterial();
  99969. if (material) {
  99970. // Alpha test
  99971. if (material.needAlphaTesting()) {
  99972. defines.push("#define ALPHATEST");
  99973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99974. attribs.push(BABYLON.VertexBuffer.UVKind);
  99975. defines.push("#define UV1");
  99976. }
  99977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  99978. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99979. defines.push("#define UV2");
  99980. }
  99981. }
  99982. //Logarithmic depth
  99983. if (material.useLogarithmicDepth) {
  99984. defines.push("#define LOGARITHMICDEPTH");
  99985. }
  99986. }
  99987. // Bones
  99988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99991. if (mesh.numBoneInfluencers > 4) {
  99992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99994. }
  99995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99996. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  99997. }
  99998. else {
  99999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100000. }
  100001. // Instances
  100002. if (useInstances) {
  100003. defines.push("#define INSTANCES");
  100004. attribs.push("world0");
  100005. attribs.push("world1");
  100006. attribs.push("world2");
  100007. attribs.push("world3");
  100008. }
  100009. // Get correct effect
  100010. var join = defines.join("\n");
  100011. if (this._cachedDefines !== join) {
  100012. this._cachedDefines = join;
  100013. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  100014. }
  100015. return this._effect.isReady();
  100016. };
  100017. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  100018. // Outline - step 1
  100019. this._savedDepthWrite = this._engine.getDepthWrite();
  100020. if (mesh.renderOutline) {
  100021. this._engine.setDepthWrite(false);
  100022. this.render(subMesh, batch);
  100023. this._engine.setDepthWrite(this._savedDepthWrite);
  100024. }
  100025. };
  100026. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  100027. // Outline - step 2
  100028. if (mesh.renderOutline && this._savedDepthWrite) {
  100029. this._engine.setDepthWrite(true);
  100030. this._engine.setColorWrite(false);
  100031. this.render(subMesh, batch);
  100032. this._engine.setColorWrite(true);
  100033. }
  100034. // Overlay
  100035. if (mesh.renderOverlay) {
  100036. var currentMode = this._engine.getAlphaMode();
  100037. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100038. this.render(subMesh, batch, true);
  100039. this._engine.setAlphaMode(currentMode);
  100040. }
  100041. };
  100042. return OutlineRenderer;
  100043. }());
  100044. BABYLON.OutlineRenderer = OutlineRenderer;
  100045. })(BABYLON || (BABYLON = {}));
  100046. //# sourceMappingURL=babylon.outlineRenderer.js.map
  100047. var BABYLON;
  100048. (function (BABYLON) {
  100049. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  100050. if (this._edgesRenderer) {
  100051. this._edgesRenderer.dispose();
  100052. this._edgesRenderer = null;
  100053. }
  100054. return this;
  100055. };
  100056. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100057. if (epsilon === void 0) { epsilon = 0.95; }
  100058. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100059. this.disableEdgesRendering();
  100060. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100061. return this;
  100062. };
  100063. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  100064. get: function () {
  100065. return this._edgesRenderer;
  100066. },
  100067. enumerable: true,
  100068. configurable: true
  100069. });
  100070. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100071. if (epsilon === void 0) { epsilon = 0.95; }
  100072. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100073. this.disableEdgesRendering();
  100074. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100075. return this;
  100076. };
  100077. /**
  100078. * FaceAdjacencies Helper class to generate edges
  100079. */
  100080. var FaceAdjacencies = /** @class */ (function () {
  100081. function FaceAdjacencies() {
  100082. this.edges = new Array();
  100083. this.edgesConnectedCount = 0;
  100084. }
  100085. return FaceAdjacencies;
  100086. }());
  100087. /**
  100088. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  100089. */
  100090. var EdgesRenderer = /** @class */ (function () {
  100091. /**
  100092. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  100093. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  100094. * @param source Mesh used to create edges
  100095. * @param epsilon sum of angles in adjacency to check for edge
  100096. * @param checkVerticesInsteadOfIndices
  100097. * @param generateEdgesLines - should generate Lines or only prepare resources.
  100098. */
  100099. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  100100. if (epsilon === void 0) { epsilon = 0.95; }
  100101. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100102. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  100103. var _this = this;
  100104. this.edgesWidthScalerForOrthographic = 1000.0;
  100105. this.edgesWidthScalerForPerspective = 50.0;
  100106. this._linesPositions = new Array();
  100107. this._linesNormals = new Array();
  100108. this._linesIndices = new Array();
  100109. this._buffers = {};
  100110. this._checkVerticesInsteadOfIndices = false;
  100111. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  100112. this.isEnabled = true;
  100113. this._source = source;
  100114. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  100115. this._epsilon = epsilon;
  100116. this._prepareRessources();
  100117. if (generateEdgesLines) {
  100118. this._generateEdgesLines();
  100119. }
  100120. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  100121. _this._rebuild();
  100122. });
  100123. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  100124. _this.dispose();
  100125. });
  100126. }
  100127. EdgesRenderer.prototype._prepareRessources = function () {
  100128. if (this._lineShader) {
  100129. return;
  100130. }
  100131. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  100132. attributes: ["position", "normal"],
  100133. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  100134. });
  100135. this._lineShader.disableDepthWrite = true;
  100136. this._lineShader.backFaceCulling = false;
  100137. };
  100138. /** @hidden */
  100139. EdgesRenderer.prototype._rebuild = function () {
  100140. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  100141. if (buffer) {
  100142. buffer._rebuild();
  100143. }
  100144. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  100145. if (buffer) {
  100146. buffer._rebuild();
  100147. }
  100148. var scene = this._source.getScene();
  100149. var engine = scene.getEngine();
  100150. this._ib = engine.createIndexBuffer(this._linesIndices);
  100151. };
  100152. /**
  100153. * Releases the required resources for the edges renderer
  100154. */
  100155. EdgesRenderer.prototype.dispose = function () {
  100156. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  100157. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  100158. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  100159. if (buffer) {
  100160. buffer.dispose();
  100161. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  100162. }
  100163. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  100164. if (buffer) {
  100165. buffer.dispose();
  100166. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  100167. }
  100168. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  100169. this._lineShader.dispose();
  100170. };
  100171. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  100172. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  100173. return 0;
  100174. }
  100175. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  100176. return 1;
  100177. }
  100178. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  100179. return 2;
  100180. }
  100181. return -1;
  100182. };
  100183. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  100184. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  100185. return 0;
  100186. }
  100187. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  100188. return 1;
  100189. }
  100190. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  100191. return 2;
  100192. }
  100193. return -1;
  100194. };
  100195. /**
  100196. * Checks if the pair of p0 and p1 is en edge
  100197. * @param faceIndex
  100198. * @param edge
  100199. * @param faceNormals
  100200. * @param p0
  100201. * @param p1
  100202. * @private
  100203. */
  100204. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  100205. var needToCreateLine;
  100206. if (edge === undefined) {
  100207. needToCreateLine = true;
  100208. }
  100209. else {
  100210. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  100211. needToCreateLine = dotProduct < this._epsilon;
  100212. }
  100213. if (needToCreateLine) {
  100214. var offset = this._linesPositions.length / 3;
  100215. var normal = p0.subtract(p1);
  100216. normal.normalize();
  100217. // Positions
  100218. this._linesPositions.push(p0.x);
  100219. this._linesPositions.push(p0.y);
  100220. this._linesPositions.push(p0.z);
  100221. this._linesPositions.push(p0.x);
  100222. this._linesPositions.push(p0.y);
  100223. this._linesPositions.push(p0.z);
  100224. this._linesPositions.push(p1.x);
  100225. this._linesPositions.push(p1.y);
  100226. this._linesPositions.push(p1.z);
  100227. this._linesPositions.push(p1.x);
  100228. this._linesPositions.push(p1.y);
  100229. this._linesPositions.push(p1.z);
  100230. // Normals
  100231. this._linesNormals.push(p1.x);
  100232. this._linesNormals.push(p1.y);
  100233. this._linesNormals.push(p1.z);
  100234. this._linesNormals.push(-1);
  100235. this._linesNormals.push(p1.x);
  100236. this._linesNormals.push(p1.y);
  100237. this._linesNormals.push(p1.z);
  100238. this._linesNormals.push(1);
  100239. this._linesNormals.push(p0.x);
  100240. this._linesNormals.push(p0.y);
  100241. this._linesNormals.push(p0.z);
  100242. this._linesNormals.push(-1);
  100243. this._linesNormals.push(p0.x);
  100244. this._linesNormals.push(p0.y);
  100245. this._linesNormals.push(p0.z);
  100246. this._linesNormals.push(1);
  100247. // Indices
  100248. this._linesIndices.push(offset);
  100249. this._linesIndices.push(offset + 1);
  100250. this._linesIndices.push(offset + 2);
  100251. this._linesIndices.push(offset);
  100252. this._linesIndices.push(offset + 2);
  100253. this._linesIndices.push(offset + 3);
  100254. }
  100255. };
  100256. /**
  100257. * Generates lines edges from adjacencjes
  100258. * @private
  100259. */
  100260. EdgesRenderer.prototype._generateEdgesLines = function () {
  100261. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100262. var indices = this._source.getIndices();
  100263. if (!indices || !positions) {
  100264. return;
  100265. }
  100266. // First let's find adjacencies
  100267. var adjacencies = new Array();
  100268. var faceNormals = new Array();
  100269. var index;
  100270. var faceAdjacencies;
  100271. // Prepare faces
  100272. for (index = 0; index < indices.length; index += 3) {
  100273. faceAdjacencies = new FaceAdjacencies();
  100274. var p0Index = indices[index];
  100275. var p1Index = indices[index + 1];
  100276. var p2Index = indices[index + 2];
  100277. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  100278. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  100279. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  100280. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  100281. faceNormal.normalize();
  100282. faceNormals.push(faceNormal);
  100283. adjacencies.push(faceAdjacencies);
  100284. }
  100285. // Scan
  100286. for (index = 0; index < adjacencies.length; index++) {
  100287. faceAdjacencies = adjacencies[index];
  100288. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  100289. var otherFaceAdjacencies = adjacencies[otherIndex];
  100290. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  100291. break;
  100292. }
  100293. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  100294. continue;
  100295. }
  100296. var otherP0 = indices[otherIndex * 3];
  100297. var otherP1 = indices[otherIndex * 3 + 1];
  100298. var otherP2 = indices[otherIndex * 3 + 2];
  100299. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  100300. var otherEdgeIndex = 0;
  100301. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  100302. continue;
  100303. }
  100304. switch (edgeIndex) {
  100305. case 0:
  100306. if (this._checkVerticesInsteadOfIndices) {
  100307. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  100308. }
  100309. else {
  100310. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  100311. }
  100312. break;
  100313. case 1:
  100314. if (this._checkVerticesInsteadOfIndices) {
  100315. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  100316. }
  100317. else {
  100318. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  100319. }
  100320. break;
  100321. case 2:
  100322. if (this._checkVerticesInsteadOfIndices) {
  100323. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  100324. }
  100325. else {
  100326. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  100327. }
  100328. break;
  100329. }
  100330. if (otherEdgeIndex === -1) {
  100331. continue;
  100332. }
  100333. faceAdjacencies.edges[edgeIndex] = otherIndex;
  100334. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  100335. faceAdjacencies.edgesConnectedCount++;
  100336. otherFaceAdjacencies.edgesConnectedCount++;
  100337. if (faceAdjacencies.edgesConnectedCount === 3) {
  100338. break;
  100339. }
  100340. }
  100341. }
  100342. }
  100343. // Create lines
  100344. for (index = 0; index < adjacencies.length; index++) {
  100345. // 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
  100346. var current = adjacencies[index];
  100347. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  100348. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  100349. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  100350. }
  100351. // Merge into a single mesh
  100352. var engine = this._source.getScene().getEngine();
  100353. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  100354. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  100355. this._ib = engine.createIndexBuffer(this._linesIndices);
  100356. this._indicesCount = this._linesIndices.length;
  100357. };
  100358. /**
  100359. * Checks wether or not the edges renderer is ready to render.
  100360. * @return true if ready, otherwise false.
  100361. */
  100362. EdgesRenderer.prototype.isReady = function () {
  100363. return this._lineShader.isReady();
  100364. };
  100365. /**
  100366. * Renders the edges of the attached mesh,
  100367. */
  100368. EdgesRenderer.prototype.render = function () {
  100369. var scene = this._source.getScene();
  100370. if (!this.isReady() || !scene.activeCamera) {
  100371. return;
  100372. }
  100373. var engine = scene.getEngine();
  100374. this._lineShader._preBind();
  100375. if (this._source.edgesColor.a !== 1) {
  100376. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100377. }
  100378. else {
  100379. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100380. }
  100381. // VBOs
  100382. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  100383. scene.resetCachedMaterial();
  100384. this._lineShader.setColor4("color", this._source.edgesColor);
  100385. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  100386. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  100387. }
  100388. else {
  100389. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  100390. }
  100391. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  100392. this._lineShader.bind(this._source.getWorldMatrix());
  100393. // Draw order
  100394. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  100395. this._lineShader.unbind();
  100396. };
  100397. return EdgesRenderer;
  100398. }());
  100399. BABYLON.EdgesRenderer = EdgesRenderer;
  100400. })(BABYLON || (BABYLON = {}));
  100401. //# sourceMappingURL=babylon.edgesRenderer.js.map
  100402. var BABYLON;
  100403. (function (BABYLON) {
  100404. /**
  100405. * FaceAdjacencies Helper class to generate edges
  100406. */
  100407. var FaceAdjacencies = /** @class */ (function () {
  100408. function FaceAdjacencies() {
  100409. this.edges = new Array();
  100410. this.edgesConnectedCount = 0;
  100411. }
  100412. return FaceAdjacencies;
  100413. }());
  100414. /**
  100415. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  100416. */
  100417. var LineEdgesRenderer = /** @class */ (function (_super) {
  100418. __extends(LineEdgesRenderer, _super);
  100419. /**
  100420. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  100421. * @param source LineMesh used to generate edges
  100422. * @param epsilon not important (specified angle for edge detection)
  100423. * @param checkVerticesInsteadOfIndices not important for LineMesh
  100424. */
  100425. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  100426. if (epsilon === void 0) { epsilon = 0.95; }
  100427. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100428. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  100429. _this._generateEdgesLines();
  100430. return _this;
  100431. }
  100432. /**
  100433. * Always create the edge since its a line so only important things are p0 and p1
  100434. * @param faceIndex not important for LineMesh
  100435. * @param edge not important for LineMesh
  100436. * @param faceNormals not important for LineMesh
  100437. * @param p0 beginnig of line
  100438. * @param p1 end of line
  100439. */
  100440. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  100441. var offset = this._linesPositions.length / 3;
  100442. var normal = p0.subtract(p1);
  100443. normal.normalize();
  100444. // Positions
  100445. this._linesPositions.push(p0.x);
  100446. this._linesPositions.push(p0.y);
  100447. this._linesPositions.push(p0.z);
  100448. this._linesPositions.push(p0.x);
  100449. this._linesPositions.push(p0.y);
  100450. this._linesPositions.push(p0.z);
  100451. this._linesPositions.push(p1.x);
  100452. this._linesPositions.push(p1.y);
  100453. this._linesPositions.push(p1.z);
  100454. this._linesPositions.push(p1.x);
  100455. this._linesPositions.push(p1.y);
  100456. this._linesPositions.push(p1.z);
  100457. // Normals
  100458. this._linesNormals.push(p1.x);
  100459. this._linesNormals.push(p1.y);
  100460. this._linesNormals.push(p1.z);
  100461. this._linesNormals.push(-1);
  100462. this._linesNormals.push(p1.x);
  100463. this._linesNormals.push(p1.y);
  100464. this._linesNormals.push(p1.z);
  100465. this._linesNormals.push(1);
  100466. this._linesNormals.push(p0.x);
  100467. this._linesNormals.push(p0.y);
  100468. this._linesNormals.push(p0.z);
  100469. this._linesNormals.push(-1);
  100470. this._linesNormals.push(p0.x);
  100471. this._linesNormals.push(p0.y);
  100472. this._linesNormals.push(p0.z);
  100473. this._linesNormals.push(1);
  100474. // Indices
  100475. this._linesIndices.push(offset);
  100476. this._linesIndices.push(offset + 1);
  100477. this._linesIndices.push(offset + 2);
  100478. this._linesIndices.push(offset);
  100479. this._linesIndices.push(offset + 2);
  100480. this._linesIndices.push(offset + 3);
  100481. };
  100482. /**
  100483. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  100484. */
  100485. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  100486. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100487. var indices = this._source.getIndices();
  100488. if (!indices || !positions) {
  100489. return;
  100490. }
  100491. // First let's find adjacencies
  100492. var adjacencies = new Array();
  100493. var faceNormals = new Array();
  100494. var index;
  100495. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  100496. var currentAdjecancy = new FaceAdjacencies();
  100497. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  100498. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  100499. adjacencies.push(currentAdjecancy);
  100500. }
  100501. // Create lines
  100502. for (index = 0; index < adjacencies.length; index++) {
  100503. // 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
  100504. var current = adjacencies[index];
  100505. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  100506. }
  100507. // Merge into a single mesh
  100508. var engine = this._source.getScene().getEngine();
  100509. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  100510. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  100511. this._ib = engine.createIndexBuffer(this._linesIndices);
  100512. this._indicesCount = this._linesIndices.length;
  100513. };
  100514. return LineEdgesRenderer;
  100515. }(BABYLON.EdgesRenderer));
  100516. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  100517. })(BABYLON || (BABYLON = {}));
  100518. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  100519. var BABYLON;
  100520. (function (BABYLON) {
  100521. // Adds the parser to the scene parsers.
  100522. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  100523. if (parsedData.effectLayers) {
  100524. if (!container.effectLayers) {
  100525. container.effectLayers = new Array();
  100526. }
  100527. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  100528. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  100529. container.effectLayers.push(effectLayer);
  100530. }
  100531. }
  100532. });
  100533. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  100534. var index = this.effectLayers.indexOf(toRemove);
  100535. if (index !== -1) {
  100536. this.effectLayers.splice(index, 1);
  100537. }
  100538. return index;
  100539. };
  100540. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  100541. this.effectLayers.push(newEffectLayer);
  100542. };
  100543. /**
  100544. * Defines the layer scene component responsible to manage any effect layers
  100545. * in a given scene.
  100546. */
  100547. var EffectLayerSceneComponent = /** @class */ (function () {
  100548. /**
  100549. * Creates a new instance of the component for the given scene
  100550. * @param scene Defines the scene to register the component in
  100551. */
  100552. function EffectLayerSceneComponent(scene) {
  100553. /**
  100554. * The component name helpfull to identify the component in the list of scene components.
  100555. */
  100556. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  100557. this._renderEffects = false;
  100558. this._needStencil = false;
  100559. this._previousStencilState = false;
  100560. this.scene = scene;
  100561. this._engine = scene.getEngine();
  100562. scene.effectLayers = new Array();
  100563. }
  100564. /**
  100565. * Registers the component in a given scene
  100566. */
  100567. EffectLayerSceneComponent.prototype.register = function () {
  100568. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  100569. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  100570. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  100571. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  100572. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  100573. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  100574. };
  100575. /**
  100576. * Rebuilds the elements related to this component in case of
  100577. * context lost for instance.
  100578. */
  100579. EffectLayerSceneComponent.prototype.rebuild = function () {
  100580. var layers = this.scene.effectLayers;
  100581. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100582. var effectLayer = layers_1[_i];
  100583. effectLayer._rebuild();
  100584. }
  100585. };
  100586. /**
  100587. * Serializes the component data to the specified json object
  100588. * @param serializationObject The object to serialize to
  100589. */
  100590. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  100591. // Effect layers
  100592. serializationObject.effectLayers = [];
  100593. var layers = this.scene.effectLayers;
  100594. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100595. var effectLayer = layers_2[_i];
  100596. if (effectLayer.serialize) {
  100597. serializationObject.effectLayers.push(effectLayer.serialize());
  100598. }
  100599. }
  100600. };
  100601. /**
  100602. * Adds all the element from the container to the scene
  100603. * @param container the container holding the elements
  100604. */
  100605. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  100606. var _this = this;
  100607. if (!container.effectLayers) {
  100608. return;
  100609. }
  100610. container.effectLayers.forEach(function (o) {
  100611. _this.scene.addEffectLayer(o);
  100612. });
  100613. };
  100614. /**
  100615. * Removes all the elements in the container from the scene
  100616. * @param container contains the elements to remove
  100617. */
  100618. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  100619. var _this = this;
  100620. if (!container.effectLayers) {
  100621. return;
  100622. }
  100623. container.effectLayers.forEach(function (o) {
  100624. _this.scene.removeEffectLayer(o);
  100625. });
  100626. };
  100627. /**
  100628. * Disposes the component and the associated ressources.
  100629. */
  100630. EffectLayerSceneComponent.prototype.dispose = function () {
  100631. var layers = this.scene.effectLayers;
  100632. while (layers.length) {
  100633. layers[0].dispose();
  100634. }
  100635. };
  100636. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  100637. var layers = this.scene.effectLayers;
  100638. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  100639. var layer = layers_3[_i];
  100640. if (!layer.hasMesh(mesh)) {
  100641. continue;
  100642. }
  100643. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  100644. var subMesh = _b[_a];
  100645. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  100646. return false;
  100647. }
  100648. }
  100649. }
  100650. return true;
  100651. };
  100652. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  100653. this._renderEffects = false;
  100654. this._needStencil = false;
  100655. var layers = this.scene.effectLayers;
  100656. if (layers && layers.length > 0) {
  100657. this._previousStencilState = this._engine.getStencilBuffer();
  100658. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  100659. var effectLayer = layers_4[_i];
  100660. if (effectLayer.shouldRender() &&
  100661. (!effectLayer.camera ||
  100662. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  100663. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  100664. this._renderEffects = true;
  100665. this._needStencil = this._needStencil || effectLayer.needStencil();
  100666. var renderTarget = effectLayer._mainTexture;
  100667. if (renderTarget._shouldRender()) {
  100668. this.scene.incrementRenderId();
  100669. renderTarget.render(false, false);
  100670. }
  100671. }
  100672. }
  100673. this.scene.incrementRenderId();
  100674. }
  100675. };
  100676. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  100677. // Activate effect Layer stencil
  100678. if (this._needStencil) {
  100679. this._engine.setStencilBuffer(true);
  100680. }
  100681. };
  100682. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  100683. // Restore effect Layer stencil
  100684. if (this._needStencil) {
  100685. this._engine.setStencilBuffer(this._previousStencilState);
  100686. }
  100687. };
  100688. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  100689. if (this._renderEffects) {
  100690. this._engine.setDepthBuffer(false);
  100691. var layers = this.scene.effectLayers;
  100692. for (var i = 0; i < layers.length; i++) {
  100693. var effectLayer = layers[i];
  100694. if (effectLayer.renderingGroupId === renderingGroupId) {
  100695. if (effectLayer.shouldRender()) {
  100696. effectLayer.render();
  100697. }
  100698. }
  100699. }
  100700. this._engine.setDepthBuffer(true);
  100701. }
  100702. };
  100703. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  100704. if (this._renderEffects) {
  100705. this._draw(-1);
  100706. }
  100707. };
  100708. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  100709. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  100710. this._draw(index);
  100711. }
  100712. };
  100713. return EffectLayerSceneComponent;
  100714. }());
  100715. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  100716. })(BABYLON || (BABYLON = {}));
  100717. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  100718. var __assign = (this && this.__assign) || function () {
  100719. __assign = Object.assign || function(t) {
  100720. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100721. s = arguments[i];
  100722. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100723. t[p] = s[p];
  100724. }
  100725. return t;
  100726. };
  100727. return __assign.apply(this, arguments);
  100728. };
  100729. var BABYLON;
  100730. (function (BABYLON) {
  100731. /**
  100732. * The effect layer Helps adding post process effect blended with the main pass.
  100733. *
  100734. * This can be for instance use to generate glow or higlight effects on the scene.
  100735. *
  100736. * The effect layer class can not be used directly and is intented to inherited from to be
  100737. * customized per effects.
  100738. */
  100739. var EffectLayer = /** @class */ (function () {
  100740. /**
  100741. * Instantiates a new effect Layer and references it in the scene.
  100742. * @param name The name of the layer
  100743. * @param scene The scene to use the layer in
  100744. */
  100745. function EffectLayer(
  100746. /** The Friendly of the effect in the scene */
  100747. name, scene) {
  100748. this._vertexBuffers = {};
  100749. this._maxSize = 0;
  100750. this._mainTextureDesiredSize = { width: 0, height: 0 };
  100751. this._shouldRender = true;
  100752. this._postProcesses = [];
  100753. this._textures = [];
  100754. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  100755. /**
  100756. * The clear color of the texture used to generate the glow map.
  100757. */
  100758. this.neutralColor = new BABYLON.Color4();
  100759. /**
  100760. * Specifies wether the highlight layer is enabled or not.
  100761. */
  100762. this.isEnabled = true;
  100763. /**
  100764. * An event triggered when the effect layer has been disposed.
  100765. */
  100766. this.onDisposeObservable = new BABYLON.Observable();
  100767. /**
  100768. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  100769. */
  100770. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  100771. /**
  100772. * An event triggered when the generated texture is being merged in the scene.
  100773. */
  100774. this.onBeforeComposeObservable = new BABYLON.Observable();
  100775. /**
  100776. * An event triggered when the generated texture has been merged in the scene.
  100777. */
  100778. this.onAfterComposeObservable = new BABYLON.Observable();
  100779. /**
  100780. * An event triggered when the efffect layer changes its size.
  100781. */
  100782. this.onSizeChangedObservable = new BABYLON.Observable();
  100783. this.name = name;
  100784. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100785. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  100786. if (!component) {
  100787. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  100788. this._scene._addComponent(component);
  100789. }
  100790. this._engine = this._scene.getEngine();
  100791. this._maxSize = this._engine.getCaps().maxTextureSize;
  100792. this._scene.effectLayers.push(this);
  100793. // Generate Buffers
  100794. this._generateIndexBuffer();
  100795. this._genrateVertexBuffer();
  100796. }
  100797. Object.defineProperty(EffectLayer.prototype, "camera", {
  100798. /**
  100799. * Gets the camera attached to the layer.
  100800. */
  100801. get: function () {
  100802. return this._effectLayerOptions.camera;
  100803. },
  100804. enumerable: true,
  100805. configurable: true
  100806. });
  100807. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  100808. /**
  100809. * Gets the rendering group id the layer should render in.
  100810. */
  100811. get: function () {
  100812. return this._effectLayerOptions.renderingGroupId;
  100813. },
  100814. enumerable: true,
  100815. configurable: true
  100816. });
  100817. /**
  100818. * Initializes the effect layer with the required options.
  100819. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  100820. */
  100821. EffectLayer.prototype._init = function (options) {
  100822. // Adapt options
  100823. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100824. this._setMainTextureSize();
  100825. this._createMainTexture();
  100826. this._createTextureAndPostProcesses();
  100827. this._mergeEffect = this._createMergeEffect();
  100828. };
  100829. /**
  100830. * Generates the index buffer of the full screen quad blending to the main canvas.
  100831. */
  100832. EffectLayer.prototype._generateIndexBuffer = function () {
  100833. // Indices
  100834. var indices = [];
  100835. indices.push(0);
  100836. indices.push(1);
  100837. indices.push(2);
  100838. indices.push(0);
  100839. indices.push(2);
  100840. indices.push(3);
  100841. this._indexBuffer = this._engine.createIndexBuffer(indices);
  100842. };
  100843. /**
  100844. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  100845. */
  100846. EffectLayer.prototype._genrateVertexBuffer = function () {
  100847. // VBO
  100848. var vertices = [];
  100849. vertices.push(1, 1);
  100850. vertices.push(-1, 1);
  100851. vertices.push(-1, -1);
  100852. vertices.push(1, -1);
  100853. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100854. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100855. };
  100856. /**
  100857. * Sets the main texture desired size which is the closest power of two
  100858. * of the engine canvas size.
  100859. */
  100860. EffectLayer.prototype._setMainTextureSize = function () {
  100861. if (this._effectLayerOptions.mainTextureFixedSize) {
  100862. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  100863. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  100864. }
  100865. else {
  100866. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  100867. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  100868. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  100869. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  100870. }
  100871. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  100872. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  100873. };
  100874. /**
  100875. * Creates the main texture for the effect layer.
  100876. */
  100877. EffectLayer.prototype._createMainTexture = function () {
  100878. var _this = this;
  100879. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  100880. width: this._mainTextureDesiredSize.width,
  100881. height: this._mainTextureDesiredSize.height
  100882. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100883. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  100884. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100885. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100886. this._mainTexture.anisotropicFilteringLevel = 1;
  100887. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100888. this._mainTexture.renderParticles = false;
  100889. this._mainTexture.renderList = null;
  100890. this._mainTexture.ignoreCameraViewport = true;
  100891. // Custom render function
  100892. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  100893. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  100894. var index;
  100895. var engine = _this._scene.getEngine();
  100896. if (depthOnlySubMeshes.length) {
  100897. engine.setColorWrite(false);
  100898. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  100899. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  100900. }
  100901. engine.setColorWrite(true);
  100902. }
  100903. for (index = 0; index < opaqueSubMeshes.length; index++) {
  100904. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  100905. }
  100906. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  100907. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  100908. }
  100909. for (index = 0; index < transparentSubMeshes.length; index++) {
  100910. _this._renderSubMesh(transparentSubMeshes.data[index]);
  100911. }
  100912. };
  100913. this._mainTexture.onClearObservable.add(function (engine) {
  100914. engine.clear(_this.neutralColor, true, true, true);
  100915. });
  100916. };
  100917. /**
  100918. * Checks for the readiness of the element composing the layer.
  100919. * @param subMesh the mesh to check for
  100920. * @param useInstances specify wether or not to use instances to render the mesh
  100921. * @param emissiveTexture the associated emissive texture used to generate the glow
  100922. * @return true if ready otherwise, false
  100923. */
  100924. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  100925. var material = subMesh.getMaterial();
  100926. if (!material) {
  100927. return false;
  100928. }
  100929. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  100930. return false;
  100931. }
  100932. var defines = [];
  100933. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100934. var mesh = subMesh.getMesh();
  100935. var uv1 = false;
  100936. var uv2 = false;
  100937. // Alpha test
  100938. if (material && material.needAlphaTesting()) {
  100939. var alphaTexture = material.getAlphaTestTexture();
  100940. if (alphaTexture) {
  100941. defines.push("#define ALPHATEST");
  100942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100943. alphaTexture.coordinatesIndex === 1) {
  100944. defines.push("#define DIFFUSEUV2");
  100945. uv2 = true;
  100946. }
  100947. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100948. defines.push("#define DIFFUSEUV1");
  100949. uv1 = true;
  100950. }
  100951. }
  100952. }
  100953. // Emissive
  100954. if (emissiveTexture) {
  100955. defines.push("#define EMISSIVE");
  100956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100957. emissiveTexture.coordinatesIndex === 1) {
  100958. defines.push("#define EMISSIVEUV2");
  100959. uv2 = true;
  100960. }
  100961. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100962. defines.push("#define EMISSIVEUV1");
  100963. uv1 = true;
  100964. }
  100965. }
  100966. if (uv1) {
  100967. attribs.push(BABYLON.VertexBuffer.UVKind);
  100968. defines.push("#define UV1");
  100969. }
  100970. if (uv2) {
  100971. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100972. defines.push("#define UV2");
  100973. }
  100974. // Bones
  100975. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100976. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100977. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100978. if (mesh.numBoneInfluencers > 4) {
  100979. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100980. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100981. }
  100982. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100983. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  100984. }
  100985. else {
  100986. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100987. }
  100988. // Morph targets
  100989. var manager = mesh.morphTargetManager;
  100990. var morphInfluencers = 0;
  100991. if (manager) {
  100992. if (manager.numInfluencers > 0) {
  100993. defines.push("#define MORPHTARGETS");
  100994. morphInfluencers = manager.numInfluencers;
  100995. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  100996. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  100997. }
  100998. }
  100999. // Instances
  101000. if (useInstances) {
  101001. defines.push("#define INSTANCES");
  101002. attribs.push("world0");
  101003. attribs.push("world1");
  101004. attribs.push("world2");
  101005. attribs.push("world3");
  101006. }
  101007. // Get correct effect
  101008. var join = defines.join("\n");
  101009. if (this._cachedDefines !== join) {
  101010. this._cachedDefines = join;
  101011. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  101012. }
  101013. return this._effectLayerMapGenerationEffect.isReady();
  101014. };
  101015. /**
  101016. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  101017. */
  101018. EffectLayer.prototype.render = function () {
  101019. var currentEffect = this._mergeEffect;
  101020. // Check
  101021. if (!currentEffect.isReady())
  101022. return;
  101023. for (var i = 0; i < this._postProcesses.length; i++) {
  101024. if (!this._postProcesses[i].isReady()) {
  101025. return;
  101026. }
  101027. }
  101028. var engine = this._scene.getEngine();
  101029. this.onBeforeComposeObservable.notifyObservers(this);
  101030. // Render
  101031. engine.enableEffect(currentEffect);
  101032. engine.setState(false);
  101033. // VBOs
  101034. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101035. // Cache
  101036. var previousAlphaMode = engine.getAlphaMode();
  101037. // Go Blend.
  101038. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  101039. // Blends the map on the main canvas.
  101040. this._internalRender(currentEffect);
  101041. // Restore Alpha
  101042. engine.setAlphaMode(previousAlphaMode);
  101043. this.onAfterComposeObservable.notifyObservers(this);
  101044. // Handle size changes.
  101045. var size = this._mainTexture.getSize();
  101046. this._setMainTextureSize();
  101047. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  101048. // Recreate RTT and post processes on size change.
  101049. this.onSizeChangedObservable.notifyObservers(this);
  101050. this._disposeTextureAndPostProcesses();
  101051. this._createMainTexture();
  101052. this._createTextureAndPostProcesses();
  101053. }
  101054. };
  101055. /**
  101056. * Determine if a given mesh will be used in the current effect.
  101057. * @param mesh mesh to test
  101058. * @returns true if the mesh will be used
  101059. */
  101060. EffectLayer.prototype.hasMesh = function (mesh) {
  101061. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  101062. return true;
  101063. }
  101064. return false;
  101065. };
  101066. /**
  101067. * Returns true if the layer contains information to display, otherwise false.
  101068. * @returns true if the glow layer should be rendered
  101069. */
  101070. EffectLayer.prototype.shouldRender = function () {
  101071. return this.isEnabled && this._shouldRender;
  101072. };
  101073. /**
  101074. * Returns true if the mesh should render, otherwise false.
  101075. * @param mesh The mesh to render
  101076. * @returns true if it should render otherwise false
  101077. */
  101078. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  101079. return true;
  101080. };
  101081. /**
  101082. * Returns true if the mesh should render, otherwise false.
  101083. * @param mesh The mesh to render
  101084. * @returns true if it should render otherwise false
  101085. */
  101086. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  101087. return true;
  101088. };
  101089. /**
  101090. * Renders the submesh passed in parameter to the generation map.
  101091. */
  101092. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  101093. var _this = this;
  101094. if (!this.shouldRender()) {
  101095. return;
  101096. }
  101097. var material = subMesh.getMaterial();
  101098. var mesh = subMesh.getRenderingMesh();
  101099. var scene = this._scene;
  101100. var engine = scene.getEngine();
  101101. if (!material) {
  101102. return;
  101103. }
  101104. // Do not block in blend mode.
  101105. if (material.needAlphaBlendingForMesh(mesh)) {
  101106. return;
  101107. }
  101108. // Culling
  101109. engine.setState(material.backFaceCulling);
  101110. // Managing instances
  101111. var batch = mesh._getInstancesRenderList(subMesh._id);
  101112. if (batch.mustReturn) {
  101113. return;
  101114. }
  101115. // Early Exit per mesh
  101116. if (!this._shouldRenderMesh(mesh)) {
  101117. return;
  101118. }
  101119. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101120. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  101121. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  101122. engine.enableEffect(this._effectLayerMapGenerationEffect);
  101123. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  101124. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  101125. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  101126. // Alpha test
  101127. if (material && material.needAlphaTesting()) {
  101128. var alphaTexture = material.getAlphaTestTexture();
  101129. if (alphaTexture) {
  101130. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  101131. var textureMatrix = alphaTexture.getTextureMatrix();
  101132. if (textureMatrix) {
  101133. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  101134. }
  101135. }
  101136. }
  101137. // Glow emissive only
  101138. if (this._emissiveTextureAndColor.texture) {
  101139. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  101140. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  101141. }
  101142. // Bones
  101143. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101144. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101145. }
  101146. // Morph targets
  101147. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  101148. // Draw
  101149. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  101150. }
  101151. else {
  101152. // Need to reset refresh rate of the main map
  101153. this._mainTexture.resetRefreshCounter();
  101154. }
  101155. };
  101156. /**
  101157. * Rebuild the required buffers.
  101158. * @hidden Internal use only.
  101159. */
  101160. EffectLayer.prototype._rebuild = function () {
  101161. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101162. if (vb) {
  101163. vb._rebuild();
  101164. }
  101165. this._generateIndexBuffer();
  101166. };
  101167. /**
  101168. * Dispose only the render target textures and post process.
  101169. */
  101170. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  101171. this._mainTexture.dispose();
  101172. for (var i = 0; i < this._postProcesses.length; i++) {
  101173. if (this._postProcesses[i]) {
  101174. this._postProcesses[i].dispose();
  101175. }
  101176. }
  101177. this._postProcesses = [];
  101178. for (var i = 0; i < this._textures.length; i++) {
  101179. if (this._textures[i]) {
  101180. this._textures[i].dispose();
  101181. }
  101182. }
  101183. this._textures = [];
  101184. };
  101185. /**
  101186. * Dispose the highlight layer and free resources.
  101187. */
  101188. EffectLayer.prototype.dispose = function () {
  101189. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101190. if (vertexBuffer) {
  101191. vertexBuffer.dispose();
  101192. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  101193. }
  101194. if (this._indexBuffer) {
  101195. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  101196. this._indexBuffer = null;
  101197. }
  101198. // Clean textures and post processes
  101199. this._disposeTextureAndPostProcesses();
  101200. // Remove from scene
  101201. var index = this._scene.effectLayers.indexOf(this, 0);
  101202. if (index > -1) {
  101203. this._scene.effectLayers.splice(index, 1);
  101204. }
  101205. // Callback
  101206. this.onDisposeObservable.notifyObservers(this);
  101207. this.onDisposeObservable.clear();
  101208. this.onBeforeRenderMainTextureObservable.clear();
  101209. this.onBeforeComposeObservable.clear();
  101210. this.onAfterComposeObservable.clear();
  101211. this.onSizeChangedObservable.clear();
  101212. };
  101213. /**
  101214. * Gets the class name of the effect layer
  101215. * @returns the string with the class name of the effect layer
  101216. */
  101217. EffectLayer.prototype.getClassName = function () {
  101218. return "EffectLayer";
  101219. };
  101220. /**
  101221. * Creates an effect layer from parsed effect layer data
  101222. * @param parsedEffectLayer defines effect layer data
  101223. * @param scene defines the current scene
  101224. * @param rootUrl defines the root URL containing the effect layer information
  101225. * @returns a parsed effect Layer
  101226. */
  101227. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  101228. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  101229. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  101230. };
  101231. __decorate([
  101232. BABYLON.serialize()
  101233. ], EffectLayer.prototype, "name", void 0);
  101234. __decorate([
  101235. BABYLON.serializeAsColor4()
  101236. ], EffectLayer.prototype, "neutralColor", void 0);
  101237. __decorate([
  101238. BABYLON.serialize()
  101239. ], EffectLayer.prototype, "isEnabled", void 0);
  101240. __decorate([
  101241. BABYLON.serializeAsCameraReference()
  101242. ], EffectLayer.prototype, "camera", null);
  101243. __decorate([
  101244. BABYLON.serialize()
  101245. ], EffectLayer.prototype, "renderingGroupId", null);
  101246. return EffectLayer;
  101247. }());
  101248. BABYLON.EffectLayer = EffectLayer;
  101249. })(BABYLON || (BABYLON = {}));
  101250. //# sourceMappingURL=babylon.effectLayer.js.map
  101251. var BABYLON;
  101252. (function (BABYLON) {
  101253. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  101254. for (var index = 0; index < this.effectLayers.length; index++) {
  101255. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  101256. return this.effectLayers[index];
  101257. }
  101258. }
  101259. return null;
  101260. };
  101261. /**
  101262. * Special Glow Blur post process only blurring the alpha channel
  101263. * It enforces keeping the most luminous color in the color channel.
  101264. */
  101265. var GlowBlurPostProcess = /** @class */ (function (_super) {
  101266. __extends(GlowBlurPostProcess, _super);
  101267. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  101268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  101269. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  101270. _this.direction = direction;
  101271. _this.kernel = kernel;
  101272. _this.onApplyObservable.add(function (effect) {
  101273. effect.setFloat2("screenSize", _this.width, _this.height);
  101274. effect.setVector2("direction", _this.direction);
  101275. effect.setFloat("blurWidth", _this.kernel);
  101276. });
  101277. return _this;
  101278. }
  101279. return GlowBlurPostProcess;
  101280. }(BABYLON.PostProcess));
  101281. /**
  101282. * The highlight layer Helps adding a glow effect around a mesh.
  101283. *
  101284. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101285. * glowy meshes to your scene.
  101286. *
  101287. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  101288. */
  101289. var HighlightLayer = /** @class */ (function (_super) {
  101290. __extends(HighlightLayer, _super);
  101291. /**
  101292. * Instantiates a new highlight Layer and references it to the scene..
  101293. * @param name The name of the layer
  101294. * @param scene The scene to use the layer in
  101295. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  101296. */
  101297. function HighlightLayer(name, scene, options) {
  101298. var _this = _super.call(this, name, scene) || this;
  101299. _this.name = name;
  101300. /**
  101301. * Specifies whether or not the inner glow is ACTIVE in the layer.
  101302. */
  101303. _this.innerGlow = true;
  101304. /**
  101305. * Specifies whether or not the outer glow is ACTIVE in the layer.
  101306. */
  101307. _this.outerGlow = true;
  101308. /**
  101309. * An event triggered when the highlight layer is being blurred.
  101310. */
  101311. _this.onBeforeBlurObservable = new BABYLON.Observable();
  101312. /**
  101313. * An event triggered when the highlight layer has been blurred.
  101314. */
  101315. _this.onAfterBlurObservable = new BABYLON.Observable();
  101316. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  101317. _this._meshes = {};
  101318. _this._excludedMeshes = {};
  101319. _this.neutralColor = HighlightLayer.NeutralColor;
  101320. // Warn on stencil
  101321. if (!_this._engine.isStencilEnable) {
  101322. 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 }");
  101323. }
  101324. // Adapt options
  101325. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  101326. // Initialize the layer
  101327. _this._init({
  101328. alphaBlendingMode: _this._options.alphaBlendingMode,
  101329. camera: _this._options.camera,
  101330. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101331. mainTextureRatio: _this._options.mainTextureRatio,
  101332. renderingGroupId: _this._options.renderingGroupId
  101333. });
  101334. // Do not render as long as no meshes have been added
  101335. _this._shouldRender = false;
  101336. return _this;
  101337. }
  101338. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  101339. /**
  101340. * Gets the horizontal size of the blur.
  101341. */
  101342. get: function () {
  101343. return this._horizontalBlurPostprocess.kernel;
  101344. },
  101345. /**
  101346. * Specifies the horizontal size of the blur.
  101347. */
  101348. set: function (value) {
  101349. this._horizontalBlurPostprocess.kernel = value;
  101350. },
  101351. enumerable: true,
  101352. configurable: true
  101353. });
  101354. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  101355. /**
  101356. * Gets the vertical size of the blur.
  101357. */
  101358. get: function () {
  101359. return this._verticalBlurPostprocess.kernel;
  101360. },
  101361. /**
  101362. * Specifies the vertical size of the blur.
  101363. */
  101364. set: function (value) {
  101365. this._verticalBlurPostprocess.kernel = value;
  101366. },
  101367. enumerable: true,
  101368. configurable: true
  101369. });
  101370. /**
  101371. * Get the effect name of the layer.
  101372. * @return The effect name
  101373. */
  101374. HighlightLayer.prototype.getEffectName = function () {
  101375. return HighlightLayer.EffectName;
  101376. };
  101377. /**
  101378. * Create the merge effect. This is the shader use to blit the information back
  101379. * to the main canvas at the end of the scene rendering.
  101380. */
  101381. HighlightLayer.prototype._createMergeEffect = function () {
  101382. // Effect
  101383. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  101384. };
  101385. /**
  101386. * Creates the render target textures and post processes used in the highlight layer.
  101387. */
  101388. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  101389. var _this = this;
  101390. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  101391. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  101392. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101393. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101394. var textureType = 0;
  101395. if (this._engine.getCaps().textureHalfFloatRender) {
  101396. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101397. }
  101398. else {
  101399. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101400. }
  101401. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  101402. width: blurTextureWidth,
  101403. height: blurTextureHeight
  101404. }, this._scene, false, true, textureType);
  101405. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101406. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101407. this._blurTexture.anisotropicFilteringLevel = 16;
  101408. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  101409. this._blurTexture.renderParticles = false;
  101410. this._blurTexture.ignoreCameraViewport = true;
  101411. this._textures = [this._blurTexture];
  101412. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  101413. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  101414. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  101415. effect.setTexture("textureSampler", _this._mainTexture);
  101416. });
  101417. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  101418. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  101419. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  101420. });
  101421. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  101422. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  101423. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  101424. });
  101425. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  101426. }
  101427. else {
  101428. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  101429. width: blurTextureWidth,
  101430. height: blurTextureHeight
  101431. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101432. this._horizontalBlurPostprocess.width = blurTextureWidth;
  101433. this._horizontalBlurPostprocess.height = blurTextureHeight;
  101434. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  101435. effect.setTexture("textureSampler", _this._mainTexture);
  101436. });
  101437. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  101438. width: blurTextureWidth,
  101439. height: blurTextureHeight
  101440. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101441. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  101442. }
  101443. this._mainTexture.onAfterUnbindObservable.add(function () {
  101444. _this.onBeforeBlurObservable.notifyObservers(_this);
  101445. var internalTexture = _this._blurTexture.getInternalTexture();
  101446. if (internalTexture) {
  101447. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  101448. }
  101449. _this.onAfterBlurObservable.notifyObservers(_this);
  101450. });
  101451. // Prevent autoClear.
  101452. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101453. };
  101454. /**
  101455. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101456. */
  101457. HighlightLayer.prototype.needStencil = function () {
  101458. return true;
  101459. };
  101460. /**
  101461. * Checks for the readiness of the element composing the layer.
  101462. * @param subMesh the mesh to check for
  101463. * @param useInstances specify wether or not to use instances to render the mesh
  101464. * @param emissiveTexture the associated emissive texture used to generate the glow
  101465. * @return true if ready otherwise, false
  101466. */
  101467. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  101468. var material = subMesh.getMaterial();
  101469. var mesh = subMesh.getRenderingMesh();
  101470. if (!material || !mesh || !this._meshes) {
  101471. return false;
  101472. }
  101473. var emissiveTexture = null;
  101474. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  101475. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  101476. emissiveTexture = material.emissiveTexture;
  101477. }
  101478. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101479. };
  101480. /**
  101481. * Implementation specific of rendering the generating effect on the main canvas.
  101482. * @param effect The effect used to render through
  101483. */
  101484. HighlightLayer.prototype._internalRender = function (effect) {
  101485. // Texture
  101486. effect.setTexture("textureSampler", this._blurTexture);
  101487. // Cache
  101488. var engine = this._engine;
  101489. var previousStencilBuffer = engine.getStencilBuffer();
  101490. var previousStencilFunction = engine.getStencilFunction();
  101491. var previousStencilMask = engine.getStencilMask();
  101492. var previousStencilOperationPass = engine.getStencilOperationPass();
  101493. var previousStencilOperationFail = engine.getStencilOperationFail();
  101494. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  101495. var previousStencilReference = engine.getStencilFunctionReference();
  101496. // Stencil operations
  101497. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  101498. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  101499. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  101500. // Draw order
  101501. engine.setStencilMask(0x00);
  101502. engine.setStencilBuffer(true);
  101503. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  101504. // 2 passes inner outer
  101505. if (this.outerGlow) {
  101506. effect.setFloat("offset", 0);
  101507. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  101508. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101509. }
  101510. if (this.innerGlow) {
  101511. effect.setFloat("offset", 1);
  101512. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  101513. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101514. }
  101515. // Restore Cache
  101516. engine.setStencilFunction(previousStencilFunction);
  101517. engine.setStencilMask(previousStencilMask);
  101518. engine.setStencilBuffer(previousStencilBuffer);
  101519. engine.setStencilOperationPass(previousStencilOperationPass);
  101520. engine.setStencilOperationFail(previousStencilOperationFail);
  101521. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  101522. engine.setStencilFunctionReference(previousStencilReference);
  101523. };
  101524. /**
  101525. * Returns true if the layer contains information to display, otherwise false.
  101526. */
  101527. HighlightLayer.prototype.shouldRender = function () {
  101528. if (_super.prototype.shouldRender.call(this)) {
  101529. return this._meshes ? true : false;
  101530. }
  101531. return false;
  101532. };
  101533. /**
  101534. * Returns true if the mesh should render, otherwise false.
  101535. * @param mesh The mesh to render
  101536. * @returns true if it should render otherwise false
  101537. */
  101538. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  101539. // Excluded Mesh
  101540. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  101541. return false;
  101542. }
  101543. ;
  101544. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101545. return false;
  101546. }
  101547. return true;
  101548. };
  101549. /**
  101550. * Sets the required values for both the emissive texture and and the main color.
  101551. */
  101552. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101553. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  101554. if (highlightLayerMesh) {
  101555. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  101556. }
  101557. else {
  101558. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101559. }
  101560. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  101561. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101562. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  101563. }
  101564. else {
  101565. this._emissiveTextureAndColor.texture = null;
  101566. }
  101567. };
  101568. /**
  101569. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  101570. * @param mesh The mesh to exclude from the highlight layer
  101571. */
  101572. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  101573. if (!this._excludedMeshes) {
  101574. return;
  101575. }
  101576. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  101577. if (!meshExcluded) {
  101578. this._excludedMeshes[mesh.uniqueId] = {
  101579. mesh: mesh,
  101580. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  101581. mesh.getEngine().setStencilBuffer(false);
  101582. }),
  101583. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  101584. mesh.getEngine().setStencilBuffer(true);
  101585. }),
  101586. };
  101587. }
  101588. };
  101589. /**
  101590. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  101591. * @param mesh The mesh to highlight
  101592. */
  101593. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  101594. if (!this._excludedMeshes) {
  101595. return;
  101596. }
  101597. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  101598. if (meshExcluded) {
  101599. if (meshExcluded.beforeRender) {
  101600. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  101601. }
  101602. if (meshExcluded.afterRender) {
  101603. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  101604. }
  101605. }
  101606. this._excludedMeshes[mesh.uniqueId] = null;
  101607. };
  101608. /**
  101609. * Determine if a given mesh will be highlighted by the current HighlightLayer
  101610. * @param mesh mesh to test
  101611. * @returns true if the mesh will be highlighted by the current HighlightLayer
  101612. */
  101613. HighlightLayer.prototype.hasMesh = function (mesh) {
  101614. if (!this._meshes) {
  101615. return false;
  101616. }
  101617. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101618. return false;
  101619. }
  101620. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  101621. };
  101622. /**
  101623. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  101624. * @param mesh The mesh to highlight
  101625. * @param color The color of the highlight
  101626. * @param glowEmissiveOnly Extract the glow from the emissive texture
  101627. */
  101628. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  101629. var _this = this;
  101630. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  101631. if (!this._meshes) {
  101632. return;
  101633. }
  101634. var meshHighlight = this._meshes[mesh.uniqueId];
  101635. if (meshHighlight) {
  101636. meshHighlight.color = color;
  101637. }
  101638. else {
  101639. this._meshes[mesh.uniqueId] = {
  101640. mesh: mesh,
  101641. color: color,
  101642. // Lambda required for capture due to Observable this context
  101643. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  101644. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  101645. _this._defaultStencilReference(mesh);
  101646. }
  101647. else {
  101648. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  101649. }
  101650. }),
  101651. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  101652. glowEmissiveOnly: glowEmissiveOnly
  101653. };
  101654. mesh.onDisposeObservable.add(function () {
  101655. _this._disposeMesh(mesh);
  101656. });
  101657. }
  101658. this._shouldRender = true;
  101659. };
  101660. /**
  101661. * Remove a mesh from the highlight layer in order to make it stop glowing.
  101662. * @param mesh The mesh to highlight
  101663. */
  101664. HighlightLayer.prototype.removeMesh = function (mesh) {
  101665. if (!this._meshes) {
  101666. return;
  101667. }
  101668. var meshHighlight = this._meshes[mesh.uniqueId];
  101669. if (meshHighlight) {
  101670. if (meshHighlight.observerHighlight) {
  101671. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101672. }
  101673. if (meshHighlight.observerDefault) {
  101674. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101675. }
  101676. delete this._meshes[mesh.uniqueId];
  101677. }
  101678. this._shouldRender = false;
  101679. for (var meshHighlightToCheck in this._meshes) {
  101680. if (this._meshes[meshHighlightToCheck]) {
  101681. this._shouldRender = true;
  101682. break;
  101683. }
  101684. }
  101685. };
  101686. /**
  101687. * Force the stencil to the normal expected value for none glowing parts
  101688. */
  101689. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  101690. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  101691. };
  101692. /**
  101693. * Free any resources and references associated to a mesh.
  101694. * Internal use
  101695. * @param mesh The mesh to free.
  101696. * @hidden
  101697. */
  101698. HighlightLayer.prototype._disposeMesh = function (mesh) {
  101699. this.removeMesh(mesh);
  101700. this.removeExcludedMesh(mesh);
  101701. };
  101702. /**
  101703. * Dispose the highlight layer and free resources.
  101704. */
  101705. HighlightLayer.prototype.dispose = function () {
  101706. if (this._meshes) {
  101707. // Clean mesh references
  101708. for (var id in this._meshes) {
  101709. var meshHighlight = this._meshes[id];
  101710. if (meshHighlight && meshHighlight.mesh) {
  101711. if (meshHighlight.observerHighlight) {
  101712. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101713. }
  101714. if (meshHighlight.observerDefault) {
  101715. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101716. }
  101717. }
  101718. }
  101719. this._meshes = null;
  101720. }
  101721. if (this._excludedMeshes) {
  101722. for (var id in this._excludedMeshes) {
  101723. var meshHighlight = this._excludedMeshes[id];
  101724. if (meshHighlight) {
  101725. if (meshHighlight.beforeRender) {
  101726. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  101727. }
  101728. if (meshHighlight.afterRender) {
  101729. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  101730. }
  101731. }
  101732. }
  101733. this._excludedMeshes = null;
  101734. }
  101735. _super.prototype.dispose.call(this);
  101736. };
  101737. /**
  101738. * Gets the class name of the effect layer
  101739. * @returns the string with the class name of the effect layer
  101740. */
  101741. HighlightLayer.prototype.getClassName = function () {
  101742. return "HighlightLayer";
  101743. };
  101744. /**
  101745. * Serializes this Highlight layer
  101746. * @returns a serialized Highlight layer object
  101747. */
  101748. HighlightLayer.prototype.serialize = function () {
  101749. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101750. serializationObject.customType = "BABYLON.HighlightLayer";
  101751. // Highlighted meshes
  101752. serializationObject.meshes = [];
  101753. if (this._meshes) {
  101754. for (var m in this._meshes) {
  101755. var mesh = this._meshes[m];
  101756. if (mesh) {
  101757. serializationObject.meshes.push({
  101758. glowEmissiveOnly: mesh.glowEmissiveOnly,
  101759. color: mesh.color.asArray(),
  101760. meshId: mesh.mesh.id
  101761. });
  101762. }
  101763. }
  101764. }
  101765. // Excluded meshes
  101766. serializationObject.excludedMeshes = [];
  101767. if (this._excludedMeshes) {
  101768. for (var e in this._excludedMeshes) {
  101769. var excludedMesh = this._excludedMeshes[e];
  101770. if (excludedMesh) {
  101771. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  101772. }
  101773. }
  101774. }
  101775. return serializationObject;
  101776. };
  101777. /**
  101778. * Creates a Highlight layer from parsed Highlight layer data
  101779. * @param parsedHightlightLayer defines the Highlight layer data
  101780. * @param scene defines the current scene
  101781. * @param rootUrl defines the root URL containing the Highlight layer information
  101782. * @returns a parsed Highlight layer
  101783. */
  101784. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  101785. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  101786. var index;
  101787. // Excluded meshes
  101788. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  101789. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  101790. if (mesh) {
  101791. hl.addExcludedMesh(mesh);
  101792. }
  101793. }
  101794. // Included meshes
  101795. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  101796. var highlightedMesh = parsedHightlightLayer.meshes[index];
  101797. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  101798. if (mesh) {
  101799. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  101800. }
  101801. }
  101802. return hl;
  101803. };
  101804. /**
  101805. * Effect Name of the highlight layer.
  101806. */
  101807. HighlightLayer.EffectName = "HighlightLayer";
  101808. /**
  101809. * The neutral color used during the preparation of the glow effect.
  101810. * This is black by default as the blend operation is a blend operation.
  101811. */
  101812. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  101813. /**
  101814. * Stencil value used for glowing meshes.
  101815. */
  101816. HighlightLayer.GlowingMeshStencilReference = 0x02;
  101817. /**
  101818. * Stencil value used for the other meshes in the scene.
  101819. */
  101820. HighlightLayer.NormalMeshStencilReference = 0x01;
  101821. __decorate([
  101822. BABYLON.serialize()
  101823. ], HighlightLayer.prototype, "innerGlow", void 0);
  101824. __decorate([
  101825. BABYLON.serialize()
  101826. ], HighlightLayer.prototype, "outerGlow", void 0);
  101827. __decorate([
  101828. BABYLON.serialize()
  101829. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  101830. __decorate([
  101831. BABYLON.serialize()
  101832. ], HighlightLayer.prototype, "blurVerticalSize", null);
  101833. __decorate([
  101834. BABYLON.serialize("options")
  101835. ], HighlightLayer.prototype, "_options", void 0);
  101836. return HighlightLayer;
  101837. }(BABYLON.EffectLayer));
  101838. BABYLON.HighlightLayer = HighlightLayer;
  101839. })(BABYLON || (BABYLON = {}));
  101840. //# sourceMappingURL=babylon.highlightLayer.js.map
  101841. var BABYLON;
  101842. (function (BABYLON) {
  101843. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  101844. for (var index = 0; index < this.effectLayers.length; index++) {
  101845. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  101846. return this.effectLayers[index];
  101847. }
  101848. }
  101849. return null;
  101850. };
  101851. /**
  101852. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  101853. *
  101854. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101855. * glowy meshes to your scene.
  101856. *
  101857. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  101858. */
  101859. var GlowLayer = /** @class */ (function (_super) {
  101860. __extends(GlowLayer, _super);
  101861. /**
  101862. * Instantiates a new glow Layer and references it to the scene.
  101863. * @param name The name of the layer
  101864. * @param scene The scene to use the layer in
  101865. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  101866. */
  101867. function GlowLayer(name, scene, options) {
  101868. var _this = _super.call(this, name, scene) || this;
  101869. _this._intensity = 1.0;
  101870. _this._includedOnlyMeshes = [];
  101871. _this._excludedMeshes = [];
  101872. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  101873. // Adapt options
  101874. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  101875. // Initialize the layer
  101876. _this._init({
  101877. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  101878. camera: _this._options.camera,
  101879. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101880. mainTextureRatio: _this._options.mainTextureRatio,
  101881. renderingGroupId: _this._options.renderingGroupId
  101882. });
  101883. return _this;
  101884. }
  101885. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  101886. /**
  101887. * Gets the kernel size of the blur.
  101888. */
  101889. get: function () {
  101890. return this._horizontalBlurPostprocess1.kernel;
  101891. },
  101892. /**
  101893. * Sets the kernel size of the blur.
  101894. */
  101895. set: function (value) {
  101896. this._horizontalBlurPostprocess1.kernel = value;
  101897. this._verticalBlurPostprocess1.kernel = value;
  101898. this._horizontalBlurPostprocess2.kernel = value;
  101899. this._verticalBlurPostprocess2.kernel = value;
  101900. },
  101901. enumerable: true,
  101902. configurable: true
  101903. });
  101904. Object.defineProperty(GlowLayer.prototype, "intensity", {
  101905. /**
  101906. * Gets the glow intensity.
  101907. */
  101908. get: function () {
  101909. return this._intensity;
  101910. },
  101911. /**
  101912. * Sets the glow intensity.
  101913. */
  101914. set: function (value) {
  101915. this._intensity = value;
  101916. },
  101917. enumerable: true,
  101918. configurable: true
  101919. });
  101920. /**
  101921. * Get the effect name of the layer.
  101922. * @return The effect name
  101923. */
  101924. GlowLayer.prototype.getEffectName = function () {
  101925. return GlowLayer.EffectName;
  101926. };
  101927. /**
  101928. * Create the merge effect. This is the shader use to blit the information back
  101929. * to the main canvas at the end of the scene rendering.
  101930. */
  101931. GlowLayer.prototype._createMergeEffect = function () {
  101932. // Effect
  101933. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  101934. };
  101935. /**
  101936. * Creates the render target textures and post processes used in the glow layer.
  101937. */
  101938. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  101939. var _this = this;
  101940. var blurTextureWidth = this._mainTextureDesiredSize.width;
  101941. var blurTextureHeight = this._mainTextureDesiredSize.height;
  101942. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101943. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101944. var textureType = 0;
  101945. if (this._engine.getCaps().textureHalfFloatRender) {
  101946. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101947. }
  101948. else {
  101949. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101950. }
  101951. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  101952. width: blurTextureWidth,
  101953. height: blurTextureHeight
  101954. }, this._scene, false, true, textureType);
  101955. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101956. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101957. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101958. this._blurTexture1.renderParticles = false;
  101959. this._blurTexture1.ignoreCameraViewport = true;
  101960. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  101961. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  101962. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  101963. width: blurTextureWidth2,
  101964. height: blurTextureHeight2
  101965. }, this._scene, false, true, textureType);
  101966. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101967. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101968. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101969. this._blurTexture2.renderParticles = false;
  101970. this._blurTexture2.ignoreCameraViewport = true;
  101971. this._textures = [this._blurTexture1, this._blurTexture2];
  101972. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101973. width: blurTextureWidth,
  101974. height: blurTextureHeight
  101975. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101976. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  101977. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  101978. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  101979. effect.setTexture("textureSampler", _this._mainTexture);
  101980. });
  101981. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101982. width: blurTextureWidth,
  101983. height: blurTextureHeight
  101984. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101985. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101986. width: blurTextureWidth2,
  101987. height: blurTextureHeight2
  101988. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101989. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  101990. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  101991. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  101992. effect.setTexture("textureSampler", _this._blurTexture1);
  101993. });
  101994. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101995. width: blurTextureWidth2,
  101996. height: blurTextureHeight2
  101997. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101998. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101999. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  102000. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102001. this._mainTexture.samples = this._options.mainTextureSamples;
  102002. this._mainTexture.onAfterUnbindObservable.add(function () {
  102003. var internalTexture = _this._blurTexture1.getInternalTexture();
  102004. if (internalTexture) {
  102005. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  102006. internalTexture = _this._blurTexture2.getInternalTexture();
  102007. if (internalTexture) {
  102008. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  102009. }
  102010. }
  102011. });
  102012. // Prevent autoClear.
  102013. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102014. };
  102015. /**
  102016. * Checks for the readiness of the element composing the layer.
  102017. * @param subMesh the mesh to check for
  102018. * @param useInstances specify wether or not to use instances to render the mesh
  102019. * @param emissiveTexture the associated emissive texture used to generate the glow
  102020. * @return true if ready otherwise, false
  102021. */
  102022. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  102023. var material = subMesh.getMaterial();
  102024. var mesh = subMesh.getRenderingMesh();
  102025. if (!material || !mesh) {
  102026. return false;
  102027. }
  102028. var emissiveTexture = material.emissiveTexture;
  102029. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102030. };
  102031. /**
  102032. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102033. */
  102034. GlowLayer.prototype.needStencil = function () {
  102035. return false;
  102036. };
  102037. /**
  102038. * Implementation specific of rendering the generating effect on the main canvas.
  102039. * @param effect The effect used to render through
  102040. */
  102041. GlowLayer.prototype._internalRender = function (effect) {
  102042. // Texture
  102043. effect.setTexture("textureSampler", this._blurTexture1);
  102044. effect.setTexture("textureSampler2", this._blurTexture2);
  102045. effect.setFloat("offset", this._intensity);
  102046. // Cache
  102047. var engine = this._engine;
  102048. var previousStencilBuffer = engine.getStencilBuffer();
  102049. // Draw order
  102050. engine.setStencilBuffer(false);
  102051. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102052. // Draw order
  102053. engine.setStencilBuffer(previousStencilBuffer);
  102054. };
  102055. /**
  102056. * Sets the required values for both the emissive texture and and the main color.
  102057. */
  102058. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102059. var textureLevel = 1.0;
  102060. if (this.customEmissiveTextureSelector) {
  102061. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  102062. }
  102063. else {
  102064. if (material) {
  102065. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102066. if (this._emissiveTextureAndColor.texture) {
  102067. textureLevel = this._emissiveTextureAndColor.texture.level;
  102068. }
  102069. }
  102070. else {
  102071. this._emissiveTextureAndColor.texture = null;
  102072. }
  102073. }
  102074. if (this.customEmissiveColorSelector) {
  102075. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  102076. }
  102077. else {
  102078. if (material.emissiveColor) {
  102079. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  102080. }
  102081. else {
  102082. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102083. }
  102084. }
  102085. };
  102086. /**
  102087. * Returns true if the mesh should render, otherwise false.
  102088. * @param mesh The mesh to render
  102089. * @returns true if it should render otherwise false
  102090. */
  102091. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  102092. return this.hasMesh(mesh);
  102093. };
  102094. /**
  102095. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  102096. * @param mesh The mesh to exclude from the glow layer
  102097. */
  102098. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  102099. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  102100. this._excludedMeshes.push(mesh.uniqueId);
  102101. }
  102102. };
  102103. /**
  102104. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  102105. * @param mesh The mesh to remove
  102106. */
  102107. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  102108. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  102109. if (index !== -1) {
  102110. this._excludedMeshes.splice(index, 1);
  102111. }
  102112. };
  102113. /**
  102114. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  102115. * @param mesh The mesh to include in the glow layer
  102116. */
  102117. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  102118. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  102119. this._includedOnlyMeshes.push(mesh.uniqueId);
  102120. }
  102121. };
  102122. /**
  102123. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  102124. * @param mesh The mesh to remove
  102125. */
  102126. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  102127. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  102128. if (index !== -1) {
  102129. this._includedOnlyMeshes.splice(index, 1);
  102130. }
  102131. };
  102132. /**
  102133. * Determine if a given mesh will be used in the glow layer
  102134. * @param mesh The mesh to test
  102135. * @returns true if the mesh will be highlighted by the current glow layer
  102136. */
  102137. GlowLayer.prototype.hasMesh = function (mesh) {
  102138. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102139. return false;
  102140. }
  102141. // Included Mesh
  102142. if (this._includedOnlyMeshes.length) {
  102143. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  102144. }
  102145. ;
  102146. // Excluded Mesh
  102147. if (this._excludedMeshes.length) {
  102148. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  102149. }
  102150. ;
  102151. return true;
  102152. };
  102153. /**
  102154. * Free any resources and references associated to a mesh.
  102155. * Internal use
  102156. * @param mesh The mesh to free.
  102157. * @hidden
  102158. */
  102159. GlowLayer.prototype._disposeMesh = function (mesh) {
  102160. this.removeIncludedOnlyMesh(mesh);
  102161. this.removeExcludedMesh(mesh);
  102162. };
  102163. /**
  102164. * Gets the class name of the effect layer
  102165. * @returns the string with the class name of the effect layer
  102166. */
  102167. GlowLayer.prototype.getClassName = function () {
  102168. return "GlowLayer";
  102169. };
  102170. /**
  102171. * Serializes this glow layer
  102172. * @returns a serialized glow layer object
  102173. */
  102174. GlowLayer.prototype.serialize = function () {
  102175. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102176. serializationObject.customType = "BABYLON.GlowLayer";
  102177. var index;
  102178. // Included meshes
  102179. serializationObject.includedMeshes = [];
  102180. if (this._includedOnlyMeshes.length) {
  102181. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  102182. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  102183. if (mesh) {
  102184. serializationObject.includedMeshes.push(mesh.id);
  102185. }
  102186. }
  102187. }
  102188. // Excluded meshes
  102189. serializationObject.excludedMeshes = [];
  102190. if (this._excludedMeshes.length) {
  102191. for (index = 0; index < this._excludedMeshes.length; index++) {
  102192. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  102193. if (mesh) {
  102194. serializationObject.excludedMeshes.push(mesh.id);
  102195. }
  102196. }
  102197. }
  102198. return serializationObject;
  102199. };
  102200. /**
  102201. * Creates a Glow Layer from parsed glow layer data
  102202. * @param parsedGlowLayer defines glow layer data
  102203. * @param scene defines the current scene
  102204. * @param rootUrl defines the root URL containing the glow layer information
  102205. * @returns a parsed Glow Layer
  102206. */
  102207. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  102208. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  102209. var index;
  102210. // Excluded meshes
  102211. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  102212. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  102213. if (mesh) {
  102214. gl.addExcludedMesh(mesh);
  102215. }
  102216. }
  102217. // Included meshes
  102218. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  102219. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  102220. if (mesh) {
  102221. gl.addIncludedOnlyMesh(mesh);
  102222. }
  102223. }
  102224. return gl;
  102225. };
  102226. /**
  102227. * Effect Name of the layer.
  102228. */
  102229. GlowLayer.EffectName = "GlowLayer";
  102230. /**
  102231. * The default blur kernel size used for the glow.
  102232. */
  102233. GlowLayer.DefaultBlurKernelSize = 32;
  102234. /**
  102235. * The default texture size ratio used for the glow.
  102236. */
  102237. GlowLayer.DefaultTextureRatio = 0.5;
  102238. __decorate([
  102239. BABYLON.serialize()
  102240. ], GlowLayer.prototype, "blurKernelSize", null);
  102241. __decorate([
  102242. BABYLON.serialize()
  102243. ], GlowLayer.prototype, "intensity", null);
  102244. __decorate([
  102245. BABYLON.serialize("options")
  102246. ], GlowLayer.prototype, "_options", void 0);
  102247. return GlowLayer;
  102248. }(BABYLON.EffectLayer));
  102249. BABYLON.GlowLayer = GlowLayer;
  102250. })(BABYLON || (BABYLON = {}));
  102251. //# sourceMappingURL=babylon.glowLayer.js.map
  102252. var BABYLON;
  102253. (function (BABYLON) {
  102254. /**
  102255. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  102256. */
  102257. var AssetTaskState;
  102258. (function (AssetTaskState) {
  102259. /**
  102260. * Initialization
  102261. */
  102262. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  102263. /**
  102264. * Running
  102265. */
  102266. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  102267. /**
  102268. * Done
  102269. */
  102270. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  102271. /**
  102272. * Error
  102273. */
  102274. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  102275. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  102276. /**
  102277. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  102278. */
  102279. var AbstractAssetTask = /** @class */ (function () {
  102280. /**
  102281. * Creates a new {BABYLON.AssetsManager}
  102282. * @param name defines the name of the task
  102283. */
  102284. function AbstractAssetTask(
  102285. /**
  102286. * Task name
  102287. */ name) {
  102288. this.name = name;
  102289. this._isCompleted = false;
  102290. this._taskState = AssetTaskState.INIT;
  102291. }
  102292. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  102293. /**
  102294. * Get if the task is completed
  102295. */
  102296. get: function () {
  102297. return this._isCompleted;
  102298. },
  102299. enumerable: true,
  102300. configurable: true
  102301. });
  102302. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  102303. /**
  102304. * Gets the current state of the task
  102305. */
  102306. get: function () {
  102307. return this._taskState;
  102308. },
  102309. enumerable: true,
  102310. configurable: true
  102311. });
  102312. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  102313. /**
  102314. * Gets the current error object (if task is in error)
  102315. */
  102316. get: function () {
  102317. return this._errorObject;
  102318. },
  102319. enumerable: true,
  102320. configurable: true
  102321. });
  102322. /**
  102323. * Internal only
  102324. * @hidden
  102325. */
  102326. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  102327. if (this._errorObject) {
  102328. return;
  102329. }
  102330. this._errorObject = {
  102331. message: message,
  102332. exception: exception
  102333. };
  102334. };
  102335. /**
  102336. * Execute the current task
  102337. * @param scene defines the scene where you want your assets to be loaded
  102338. * @param onSuccess is a callback called when the task is successfully executed
  102339. * @param onError is a callback called if an error occurs
  102340. */
  102341. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  102342. var _this = this;
  102343. this._taskState = AssetTaskState.RUNNING;
  102344. this.runTask(scene, function () {
  102345. _this.onDoneCallback(onSuccess, onError);
  102346. }, function (msg, exception) {
  102347. _this.onErrorCallback(onError, msg, exception);
  102348. });
  102349. };
  102350. /**
  102351. * Execute the current task
  102352. * @param scene defines the scene where you want your assets to be loaded
  102353. * @param onSuccess is a callback called when the task is successfully executed
  102354. * @param onError is a callback called if an error occurs
  102355. */
  102356. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102357. throw new Error("runTask is not implemented");
  102358. };
  102359. /**
  102360. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  102361. * This can be used with failed tasks that have the reason for failure fixed.
  102362. */
  102363. AbstractAssetTask.prototype.reset = function () {
  102364. this._taskState = AssetTaskState.INIT;
  102365. };
  102366. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  102367. this._taskState = AssetTaskState.ERROR;
  102368. this._errorObject = {
  102369. message: message,
  102370. exception: exception
  102371. };
  102372. if (this.onError) {
  102373. this.onError(this, message, exception);
  102374. }
  102375. onError();
  102376. };
  102377. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  102378. try {
  102379. this._taskState = AssetTaskState.DONE;
  102380. this._isCompleted = true;
  102381. if (this.onSuccess) {
  102382. this.onSuccess(this);
  102383. }
  102384. onSuccess();
  102385. }
  102386. catch (e) {
  102387. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  102388. }
  102389. };
  102390. return AbstractAssetTask;
  102391. }());
  102392. BABYLON.AbstractAssetTask = AbstractAssetTask;
  102393. /**
  102394. * Class used to share progress information about assets loading
  102395. */
  102396. var AssetsProgressEvent = /** @class */ (function () {
  102397. /**
  102398. * Creates a {BABYLON.AssetsProgressEvent}
  102399. * @param remainingCount defines the number of remaining tasks to process
  102400. * @param totalCount defines the total number of tasks
  102401. * @param task defines the task that was just processed
  102402. */
  102403. function AssetsProgressEvent(remainingCount, totalCount, task) {
  102404. this.remainingCount = remainingCount;
  102405. this.totalCount = totalCount;
  102406. this.task = task;
  102407. }
  102408. return AssetsProgressEvent;
  102409. }());
  102410. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  102411. /**
  102412. * Define a task used by {BABYLON.AssetsManager} to load meshes
  102413. */
  102414. var MeshAssetTask = /** @class */ (function (_super) {
  102415. __extends(MeshAssetTask, _super);
  102416. /**
  102417. * Creates a new {BABYLON.MeshAssetTask}
  102418. * @param name defines the name of the task
  102419. * @param meshesNames defines the list of mesh's names you want to load
  102420. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  102421. * @param sceneFilename defines the filename of the scene to load from
  102422. */
  102423. function MeshAssetTask(
  102424. /**
  102425. * Defines the name of the task
  102426. */
  102427. name,
  102428. /**
  102429. * Defines the list of mesh's names you want to load
  102430. */
  102431. meshesNames,
  102432. /**
  102433. * Defines the root url to use as a base to load your meshes and associated resources
  102434. */
  102435. rootUrl,
  102436. /**
  102437. * Defines the filename of the scene to load from
  102438. */
  102439. sceneFilename) {
  102440. var _this = _super.call(this, name) || this;
  102441. _this.name = name;
  102442. _this.meshesNames = meshesNames;
  102443. _this.rootUrl = rootUrl;
  102444. _this.sceneFilename = sceneFilename;
  102445. return _this;
  102446. }
  102447. /**
  102448. * Execute the current task
  102449. * @param scene defines the scene where you want your assets to be loaded
  102450. * @param onSuccess is a callback called when the task is successfully executed
  102451. * @param onError is a callback called if an error occurs
  102452. */
  102453. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102454. var _this = this;
  102455. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  102456. _this.loadedMeshes = meshes;
  102457. _this.loadedParticleSystems = particleSystems;
  102458. _this.loadedSkeletons = skeletons;
  102459. onSuccess();
  102460. }, null, function (scene, message, exception) {
  102461. onError(message, exception);
  102462. });
  102463. };
  102464. return MeshAssetTask;
  102465. }(AbstractAssetTask));
  102466. BABYLON.MeshAssetTask = MeshAssetTask;
  102467. /**
  102468. * Define a task used by {BABYLON.AssetsManager} to load text content
  102469. */
  102470. var TextFileAssetTask = /** @class */ (function (_super) {
  102471. __extends(TextFileAssetTask, _super);
  102472. /**
  102473. * Creates a new TextFileAssetTask object
  102474. * @param name defines the name of the task
  102475. * @param url defines the location of the file to load
  102476. */
  102477. function TextFileAssetTask(
  102478. /**
  102479. * Defines the name of the task
  102480. */
  102481. name,
  102482. /**
  102483. * Defines the location of the file to load
  102484. */
  102485. url) {
  102486. var _this = _super.call(this, name) || this;
  102487. _this.name = name;
  102488. _this.url = url;
  102489. return _this;
  102490. }
  102491. /**
  102492. * Execute the current task
  102493. * @param scene defines the scene where you want your assets to be loaded
  102494. * @param onSuccess is a callback called when the task is successfully executed
  102495. * @param onError is a callback called if an error occurs
  102496. */
  102497. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102498. var _this = this;
  102499. scene._loadFile(this.url, function (data) {
  102500. _this.text = data;
  102501. onSuccess();
  102502. }, undefined, false, false, function (request, exception) {
  102503. if (request) {
  102504. onError(request.status + " " + request.statusText, exception);
  102505. }
  102506. });
  102507. };
  102508. return TextFileAssetTask;
  102509. }(AbstractAssetTask));
  102510. BABYLON.TextFileAssetTask = TextFileAssetTask;
  102511. /**
  102512. * Define a task used by {BABYLON.AssetsManager} to load binary data
  102513. */
  102514. var BinaryFileAssetTask = /** @class */ (function (_super) {
  102515. __extends(BinaryFileAssetTask, _super);
  102516. /**
  102517. * Creates a new BinaryFileAssetTask object
  102518. * @param name defines the name of the new task
  102519. * @param url defines the location of the file to load
  102520. */
  102521. function BinaryFileAssetTask(
  102522. /**
  102523. * Defines the name of the task
  102524. */
  102525. name,
  102526. /**
  102527. * Defines the location of the file to load
  102528. */
  102529. url) {
  102530. var _this = _super.call(this, name) || this;
  102531. _this.name = name;
  102532. _this.url = url;
  102533. return _this;
  102534. }
  102535. /**
  102536. * Execute the current task
  102537. * @param scene defines the scene where you want your assets to be loaded
  102538. * @param onSuccess is a callback called when the task is successfully executed
  102539. * @param onError is a callback called if an error occurs
  102540. */
  102541. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102542. var _this = this;
  102543. scene._loadFile(this.url, function (data) {
  102544. _this.data = data;
  102545. onSuccess();
  102546. }, undefined, true, true, function (request, exception) {
  102547. if (request) {
  102548. onError(request.status + " " + request.statusText, exception);
  102549. }
  102550. });
  102551. };
  102552. return BinaryFileAssetTask;
  102553. }(AbstractAssetTask));
  102554. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  102555. /**
  102556. * Define a task used by {BABYLON.AssetsManager} to load images
  102557. */
  102558. var ImageAssetTask = /** @class */ (function (_super) {
  102559. __extends(ImageAssetTask, _super);
  102560. /**
  102561. * Creates a new ImageAssetTask
  102562. * @param name defines the name of the task
  102563. * @param url defines the location of the image to load
  102564. */
  102565. function ImageAssetTask(
  102566. /**
  102567. * Defines the name of the task
  102568. */
  102569. name,
  102570. /**
  102571. * Defines the location of the image to load
  102572. */
  102573. url) {
  102574. var _this = _super.call(this, name) || this;
  102575. _this.name = name;
  102576. _this.url = url;
  102577. return _this;
  102578. }
  102579. /**
  102580. * Execute the current task
  102581. * @param scene defines the scene where you want your assets to be loaded
  102582. * @param onSuccess is a callback called when the task is successfully executed
  102583. * @param onError is a callback called if an error occurs
  102584. */
  102585. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102586. var _this = this;
  102587. var img = new Image();
  102588. BABYLON.Tools.SetCorsBehavior(this.url, img);
  102589. img.onload = function () {
  102590. _this.image = img;
  102591. onSuccess();
  102592. };
  102593. img.onerror = function (err) {
  102594. onError("Error loading image", err);
  102595. };
  102596. img.src = this.url;
  102597. };
  102598. return ImageAssetTask;
  102599. }(AbstractAssetTask));
  102600. BABYLON.ImageAssetTask = ImageAssetTask;
  102601. /**
  102602. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  102603. */
  102604. var TextureAssetTask = /** @class */ (function (_super) {
  102605. __extends(TextureAssetTask, _super);
  102606. /**
  102607. * Creates a new TextureAssetTask object
  102608. * @param name defines the name of the task
  102609. * @param url defines the location of the file to load
  102610. * @param noMipmap defines if mipmap should not be generated (default is false)
  102611. * @param invertY defines if texture must be inverted on Y axis (default is false)
  102612. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  102613. */
  102614. function TextureAssetTask(
  102615. /**
  102616. * Defines the name of the task
  102617. */
  102618. name,
  102619. /**
  102620. * Defines the location of the file to load
  102621. */
  102622. url,
  102623. /**
  102624. * Defines if mipmap should not be generated (default is false)
  102625. */
  102626. noMipmap,
  102627. /**
  102628. * Defines if texture must be inverted on Y axis (default is false)
  102629. */
  102630. invertY,
  102631. /**
  102632. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  102633. */
  102634. samplingMode) {
  102635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102636. var _this = _super.call(this, name) || this;
  102637. _this.name = name;
  102638. _this.url = url;
  102639. _this.noMipmap = noMipmap;
  102640. _this.invertY = invertY;
  102641. _this.samplingMode = samplingMode;
  102642. return _this;
  102643. }
  102644. /**
  102645. * Execute the current task
  102646. * @param scene defines the scene where you want your assets to be loaded
  102647. * @param onSuccess is a callback called when the task is successfully executed
  102648. * @param onError is a callback called if an error occurs
  102649. */
  102650. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102651. var onload = function () {
  102652. onSuccess();
  102653. };
  102654. var onerror = function (message, exception) {
  102655. onError(message, exception);
  102656. };
  102657. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  102658. };
  102659. return TextureAssetTask;
  102660. }(AbstractAssetTask));
  102661. BABYLON.TextureAssetTask = TextureAssetTask;
  102662. /**
  102663. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  102664. */
  102665. var CubeTextureAssetTask = /** @class */ (function (_super) {
  102666. __extends(CubeTextureAssetTask, _super);
  102667. /**
  102668. * Creates a new CubeTextureAssetTask
  102669. * @param name defines the name of the task
  102670. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102671. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102672. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102673. * @param files defines the explicit list of files (undefined by default)
  102674. */
  102675. function CubeTextureAssetTask(
  102676. /**
  102677. * Defines the name of the task
  102678. */
  102679. name,
  102680. /**
  102681. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102682. */
  102683. url,
  102684. /**
  102685. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102686. */
  102687. extensions,
  102688. /**
  102689. * Defines if mipmaps should not be generated (default is false)
  102690. */
  102691. noMipmap,
  102692. /**
  102693. * Defines the explicit list of files (undefined by default)
  102694. */
  102695. files) {
  102696. var _this = _super.call(this, name) || this;
  102697. _this.name = name;
  102698. _this.url = url;
  102699. _this.extensions = extensions;
  102700. _this.noMipmap = noMipmap;
  102701. _this.files = files;
  102702. return _this;
  102703. }
  102704. /**
  102705. * Execute the current task
  102706. * @param scene defines the scene where you want your assets to be loaded
  102707. * @param onSuccess is a callback called when the task is successfully executed
  102708. * @param onError is a callback called if an error occurs
  102709. */
  102710. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102711. var onload = function () {
  102712. onSuccess();
  102713. };
  102714. var onerror = function (message, exception) {
  102715. onError(message, exception);
  102716. };
  102717. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  102718. };
  102719. return CubeTextureAssetTask;
  102720. }(AbstractAssetTask));
  102721. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  102722. /**
  102723. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  102724. */
  102725. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  102726. __extends(HDRCubeTextureAssetTask, _super);
  102727. /**
  102728. * Creates a new HDRCubeTextureAssetTask object
  102729. * @param name defines the name of the task
  102730. * @param url defines the location of the file to load
  102731. * @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.
  102732. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102733. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102734. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  102735. * @param reserved Internal use only
  102736. */
  102737. function HDRCubeTextureAssetTask(
  102738. /**
  102739. * Defines the name of the task
  102740. */
  102741. name,
  102742. /**
  102743. * Defines the location of the file to load
  102744. */
  102745. url,
  102746. /**
  102747. * Defines the desired size (the more it increases the longer the generation will be)
  102748. */
  102749. size,
  102750. /**
  102751. * Defines if mipmaps should not be generated (default is false)
  102752. */
  102753. noMipmap,
  102754. /**
  102755. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102756. */
  102757. generateHarmonics,
  102758. /**
  102759. * 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)
  102760. */
  102761. gammaSpace,
  102762. /**
  102763. * Internal Use Only
  102764. */
  102765. reserved) {
  102766. if (noMipmap === void 0) { noMipmap = false; }
  102767. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102768. if (gammaSpace === void 0) { gammaSpace = false; }
  102769. if (reserved === void 0) { reserved = false; }
  102770. var _this = _super.call(this, name) || this;
  102771. _this.name = name;
  102772. _this.url = url;
  102773. _this.size = size;
  102774. _this.noMipmap = noMipmap;
  102775. _this.generateHarmonics = generateHarmonics;
  102776. _this.gammaSpace = gammaSpace;
  102777. _this.reserved = reserved;
  102778. return _this;
  102779. }
  102780. /**
  102781. * Execute the current task
  102782. * @param scene defines the scene where you want your assets to be loaded
  102783. * @param onSuccess is a callback called when the task is successfully executed
  102784. * @param onError is a callback called if an error occurs
  102785. */
  102786. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  102787. var onload = function () {
  102788. onSuccess();
  102789. };
  102790. var onerror = function (message, exception) {
  102791. onError(message, exception);
  102792. };
  102793. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  102794. };
  102795. return HDRCubeTextureAssetTask;
  102796. }(AbstractAssetTask));
  102797. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  102798. /**
  102799. * This class can be used to easily import assets into a scene
  102800. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  102801. */
  102802. var AssetsManager = /** @class */ (function () {
  102803. /**
  102804. * Creates a new AssetsManager
  102805. * @param scene defines the scene to work on
  102806. */
  102807. function AssetsManager(scene) {
  102808. this._isLoading = false;
  102809. this._tasks = new Array();
  102810. this._waitingTasksCount = 0;
  102811. this._totalTasksCount = 0;
  102812. /**
  102813. * Observable called when all tasks are processed
  102814. */
  102815. this.onTaskSuccessObservable = new BABYLON.Observable();
  102816. /**
  102817. * Observable called when a task had an error
  102818. */
  102819. this.onTaskErrorObservable = new BABYLON.Observable();
  102820. /**
  102821. * Observable called when a task is successful
  102822. */
  102823. this.onTasksDoneObservable = new BABYLON.Observable();
  102824. /**
  102825. * Observable called when a task is done (whatever the result is)
  102826. */
  102827. this.onProgressObservable = new BABYLON.Observable();
  102828. /**
  102829. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  102830. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  102831. */
  102832. this.useDefaultLoadingScreen = true;
  102833. this._scene = scene;
  102834. }
  102835. /**
  102836. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  102837. * @param taskName defines the name of the new task
  102838. * @param meshesNames defines the name of meshes to load
  102839. * @param rootUrl defines the root url to use to locate files
  102840. * @param sceneFilename defines the filename of the scene file
  102841. * @returns a new {BABYLON.MeshAssetTask} object
  102842. */
  102843. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  102844. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  102845. this._tasks.push(task);
  102846. return task;
  102847. };
  102848. /**
  102849. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  102850. * @param taskName defines the name of the new task
  102851. * @param url defines the url of the file to load
  102852. * @returns a new {BABYLON.TextFileAssetTask} object
  102853. */
  102854. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  102855. var task = new TextFileAssetTask(taskName, url);
  102856. this._tasks.push(task);
  102857. return task;
  102858. };
  102859. /**
  102860. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  102861. * @param taskName defines the name of the new task
  102862. * @param url defines the url of the file to load
  102863. * @returns a new {BABYLON.BinaryFileAssetTask} object
  102864. */
  102865. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  102866. var task = new BinaryFileAssetTask(taskName, url);
  102867. this._tasks.push(task);
  102868. return task;
  102869. };
  102870. /**
  102871. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  102872. * @param taskName defines the name of the new task
  102873. * @param url defines the url of the file to load
  102874. * @returns a new {BABYLON.ImageAssetTask} object
  102875. */
  102876. AssetsManager.prototype.addImageTask = function (taskName, url) {
  102877. var task = new ImageAssetTask(taskName, url);
  102878. this._tasks.push(task);
  102879. return task;
  102880. };
  102881. /**
  102882. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  102883. * @param taskName defines the name of the new task
  102884. * @param url defines the url of the file to load
  102885. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102886. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  102887. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  102888. * @returns a new {BABYLON.TextureAssetTask} object
  102889. */
  102890. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  102891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102892. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  102893. this._tasks.push(task);
  102894. return task;
  102895. };
  102896. /**
  102897. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  102898. * @param taskName defines the name of the new task
  102899. * @param url defines the url of the file to load
  102900. * @param extensions defines the extension to use to load the cube map (can be null)
  102901. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102902. * @param files defines the list of files to load (can be null)
  102903. * @returns a new {BABYLON.CubeTextureAssetTask} object
  102904. */
  102905. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  102906. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  102907. this._tasks.push(task);
  102908. return task;
  102909. };
  102910. /**
  102911. *
  102912. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  102913. * @param taskName defines the name of the new task
  102914. * @param url defines the url of the file to load
  102915. * @param size defines the size you want for the cubemap (can be null)
  102916. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102917. * @param generateHarmonics defines if you want to automatically generate (true by default)
  102918. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  102919. * @param reserved Internal use only
  102920. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  102921. */
  102922. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  102923. if (noMipmap === void 0) { noMipmap = false; }
  102924. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102925. if (gammaSpace === void 0) { gammaSpace = false; }
  102926. if (reserved === void 0) { reserved = false; }
  102927. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  102928. this._tasks.push(task);
  102929. return task;
  102930. };
  102931. /**
  102932. * Remove a task from the assets manager.
  102933. * @param task the task to remove
  102934. */
  102935. AssetsManager.prototype.removeTask = function (task) {
  102936. var index = this._tasks.indexOf(task);
  102937. if (index > -1) {
  102938. this._tasks.splice(index, 1);
  102939. }
  102940. };
  102941. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  102942. this._waitingTasksCount--;
  102943. try {
  102944. if (this.onProgress) {
  102945. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  102946. }
  102947. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  102948. }
  102949. catch (e) {
  102950. BABYLON.Tools.Error("Error running progress callbacks.");
  102951. console.log(e);
  102952. }
  102953. if (this._waitingTasksCount === 0) {
  102954. try {
  102955. if (this.onFinish) {
  102956. this.onFinish(this._tasks);
  102957. }
  102958. // Let's remove successfull tasks
  102959. var currentTasks = this._tasks.slice();
  102960. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  102961. var task = currentTasks_1[_i];
  102962. if (task.taskState === AssetTaskState.DONE) {
  102963. var index = this._tasks.indexOf(task);
  102964. if (index > -1) {
  102965. this._tasks.splice(index, 1);
  102966. }
  102967. }
  102968. }
  102969. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102970. }
  102971. catch (e) {
  102972. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  102973. console.log(e);
  102974. }
  102975. this._isLoading = false;
  102976. this._scene.getEngine().hideLoadingUI();
  102977. }
  102978. };
  102979. AssetsManager.prototype._runTask = function (task) {
  102980. var _this = this;
  102981. var done = function () {
  102982. try {
  102983. if (_this.onTaskSuccess) {
  102984. _this.onTaskSuccess(task);
  102985. }
  102986. _this.onTaskSuccessObservable.notifyObservers(task);
  102987. _this._decreaseWaitingTasksCount(task);
  102988. }
  102989. catch (e) {
  102990. error("Error executing task success callbacks", e);
  102991. }
  102992. };
  102993. var error = function (message, exception) {
  102994. task._setErrorObject(message, exception);
  102995. if (_this.onTaskError) {
  102996. _this.onTaskError(task);
  102997. }
  102998. _this.onTaskErrorObservable.notifyObservers(task);
  102999. _this._decreaseWaitingTasksCount(task);
  103000. };
  103001. task.run(this._scene, done, error);
  103002. };
  103003. /**
  103004. * Reset the {BABYLON.AssetsManager} and remove all tasks
  103005. * @return the current instance of the {BABYLON.AssetsManager}
  103006. */
  103007. AssetsManager.prototype.reset = function () {
  103008. this._isLoading = false;
  103009. this._tasks = new Array();
  103010. return this;
  103011. };
  103012. /**
  103013. * Start the loading process
  103014. * @return the current instance of the {BABYLON.AssetsManager}
  103015. */
  103016. AssetsManager.prototype.load = function () {
  103017. if (this._isLoading) {
  103018. return this;
  103019. }
  103020. this._isLoading = true;
  103021. this._waitingTasksCount = this._tasks.length;
  103022. this._totalTasksCount = this._tasks.length;
  103023. if (this._waitingTasksCount === 0) {
  103024. this._isLoading = false;
  103025. if (this.onFinish) {
  103026. this.onFinish(this._tasks);
  103027. }
  103028. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103029. return this;
  103030. }
  103031. if (this.useDefaultLoadingScreen) {
  103032. this._scene.getEngine().displayLoadingUI();
  103033. }
  103034. for (var index = 0; index < this._tasks.length; index++) {
  103035. var task = this._tasks[index];
  103036. if (task.taskState === AssetTaskState.INIT) {
  103037. this._runTask(task);
  103038. }
  103039. }
  103040. return this;
  103041. };
  103042. return AssetsManager;
  103043. }());
  103044. BABYLON.AssetsManager = AssetsManager;
  103045. })(BABYLON || (BABYLON = {}));
  103046. //# sourceMappingURL=babylon.assetsManager.js.map
  103047. var BABYLON;
  103048. (function (BABYLON) {
  103049. var serializedGeometries = [];
  103050. var serializeGeometry = function (geometry, serializationGeometries) {
  103051. if (serializedGeometries[geometry.id]) {
  103052. return;
  103053. }
  103054. if (geometry.doNotSerialize) {
  103055. return;
  103056. }
  103057. if (geometry instanceof BABYLON.BoxGeometry) {
  103058. serializationGeometries.boxes.push(geometry.serialize());
  103059. }
  103060. else if (geometry instanceof BABYLON.SphereGeometry) {
  103061. serializationGeometries.spheres.push(geometry.serialize());
  103062. }
  103063. else if (geometry instanceof BABYLON.CylinderGeometry) {
  103064. serializationGeometries.cylinders.push(geometry.serialize());
  103065. }
  103066. else if (geometry instanceof BABYLON.TorusGeometry) {
  103067. serializationGeometries.toruses.push(geometry.serialize());
  103068. }
  103069. else if (geometry instanceof BABYLON.GroundGeometry) {
  103070. serializationGeometries.grounds.push(geometry.serialize());
  103071. }
  103072. else if (geometry instanceof BABYLON.Plane) {
  103073. serializationGeometries.planes.push(geometry.serialize());
  103074. }
  103075. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  103076. serializationGeometries.torusKnots.push(geometry.serialize());
  103077. }
  103078. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  103079. throw new Error("Unknown primitive type");
  103080. }
  103081. else {
  103082. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  103083. }
  103084. serializedGeometries[geometry.id] = true;
  103085. };
  103086. var serializeMesh = function (mesh, serializationScene) {
  103087. var serializationObject = {};
  103088. // Geometry
  103089. var geometry = mesh._geometry;
  103090. if (geometry) {
  103091. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  103092. // 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
  103093. serializeGeometry(geometry, serializationScene.geometries);
  103094. }
  103095. }
  103096. // Custom
  103097. if (mesh.serialize) {
  103098. mesh.serialize(serializationObject);
  103099. }
  103100. return serializationObject;
  103101. };
  103102. var finalizeSingleMesh = function (mesh, serializationObject) {
  103103. //only works if the mesh is already loaded
  103104. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  103105. //serialize material
  103106. if (mesh.material) {
  103107. if (mesh.material instanceof BABYLON.MultiMaterial) {
  103108. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  103109. serializationObject.materials = serializationObject.materials || [];
  103110. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103111. serializationObject.multiMaterials.push(mesh.material.serialize());
  103112. var _loop_1 = function (submaterial) {
  103113. if (submaterial) {
  103114. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  103115. serializationObject.materials.push(submaterial.serialize());
  103116. }
  103117. }
  103118. };
  103119. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  103120. var submaterial = _a[_i];
  103121. _loop_1(submaterial);
  103122. }
  103123. }
  103124. }
  103125. else {
  103126. serializationObject.materials = serializationObject.materials || [];
  103127. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103128. serializationObject.materials.push(mesh.material.serialize());
  103129. }
  103130. }
  103131. }
  103132. //serialize geometry
  103133. var geometry = mesh._geometry;
  103134. if (geometry) {
  103135. if (!serializationObject.geometries) {
  103136. serializationObject.geometries = {};
  103137. serializationObject.geometries.boxes = [];
  103138. serializationObject.geometries.spheres = [];
  103139. serializationObject.geometries.cylinders = [];
  103140. serializationObject.geometries.toruses = [];
  103141. serializationObject.geometries.grounds = [];
  103142. serializationObject.geometries.planes = [];
  103143. serializationObject.geometries.torusKnots = [];
  103144. serializationObject.geometries.vertexData = [];
  103145. }
  103146. serializeGeometry(geometry, serializationObject.geometries);
  103147. }
  103148. // Skeletons
  103149. if (mesh.skeleton) {
  103150. serializationObject.skeletons = serializationObject.skeletons || [];
  103151. serializationObject.skeletons.push(mesh.skeleton.serialize());
  103152. }
  103153. //serialize the actual mesh
  103154. serializationObject.meshes = serializationObject.meshes || [];
  103155. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  103156. }
  103157. };
  103158. var SceneSerializer = /** @class */ (function () {
  103159. function SceneSerializer() {
  103160. }
  103161. SceneSerializer.ClearCache = function () {
  103162. serializedGeometries = [];
  103163. };
  103164. SceneSerializer.Serialize = function (scene) {
  103165. var serializationObject = {};
  103166. SceneSerializer.ClearCache();
  103167. // Scene
  103168. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  103169. serializationObject.autoClear = scene.autoClear;
  103170. serializationObject.clearColor = scene.clearColor.asArray();
  103171. serializationObject.ambientColor = scene.ambientColor.asArray();
  103172. serializationObject.gravity = scene.gravity.asArray();
  103173. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  103174. serializationObject.workerCollisions = scene.workerCollisions;
  103175. // Fog
  103176. if (scene.fogMode && scene.fogMode !== 0) {
  103177. serializationObject.fogMode = scene.fogMode;
  103178. serializationObject.fogColor = scene.fogColor.asArray();
  103179. serializationObject.fogStart = scene.fogStart;
  103180. serializationObject.fogEnd = scene.fogEnd;
  103181. serializationObject.fogDensity = scene.fogDensity;
  103182. }
  103183. //Physics
  103184. if (scene.isPhysicsEnabled()) {
  103185. var physicEngine = scene.getPhysicsEngine();
  103186. if (physicEngine) {
  103187. serializationObject.physicsEnabled = true;
  103188. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  103189. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  103190. }
  103191. }
  103192. // Metadata
  103193. if (scene.metadata) {
  103194. serializationObject.metadata = scene.metadata;
  103195. }
  103196. // Morph targets
  103197. serializationObject.morphTargetManagers = [];
  103198. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  103199. var abstractMesh = _a[_i];
  103200. var manager = abstractMesh.morphTargetManager;
  103201. if (manager) {
  103202. serializationObject.morphTargetManagers.push(manager.serialize());
  103203. }
  103204. }
  103205. // Lights
  103206. serializationObject.lights = [];
  103207. var index;
  103208. var light;
  103209. for (index = 0; index < scene.lights.length; index++) {
  103210. light = scene.lights[index];
  103211. if (!light.doNotSerialize) {
  103212. serializationObject.lights.push(light.serialize());
  103213. }
  103214. }
  103215. // Cameras
  103216. serializationObject.cameras = [];
  103217. for (index = 0; index < scene.cameras.length; index++) {
  103218. var camera = scene.cameras[index];
  103219. if (!camera.doNotSerialize) {
  103220. serializationObject.cameras.push(camera.serialize());
  103221. }
  103222. }
  103223. if (scene.activeCamera) {
  103224. serializationObject.activeCameraID = scene.activeCamera.id;
  103225. }
  103226. // Animations
  103227. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  103228. // Materials
  103229. serializationObject.materials = [];
  103230. serializationObject.multiMaterials = [];
  103231. var material;
  103232. for (index = 0; index < scene.materials.length; index++) {
  103233. material = scene.materials[index];
  103234. if (!material.doNotSerialize) {
  103235. serializationObject.materials.push(material.serialize());
  103236. }
  103237. }
  103238. // MultiMaterials
  103239. serializationObject.multiMaterials = [];
  103240. for (index = 0; index < scene.multiMaterials.length; index++) {
  103241. var multiMaterial = scene.multiMaterials[index];
  103242. serializationObject.multiMaterials.push(multiMaterial.serialize());
  103243. }
  103244. // Environment texture
  103245. if (scene.environmentTexture) {
  103246. serializationObject.environmentTexture = scene.environmentTexture.name;
  103247. }
  103248. // Skeletons
  103249. serializationObject.skeletons = [];
  103250. for (index = 0; index < scene.skeletons.length; index++) {
  103251. var skeleton = scene.skeletons[index];
  103252. if (!skeleton.doNotSerialize) {
  103253. serializationObject.skeletons.push(skeleton.serialize());
  103254. }
  103255. }
  103256. // Transform nodes
  103257. serializationObject.transformNodes = [];
  103258. for (index = 0; index < scene.transformNodes.length; index++) {
  103259. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  103260. }
  103261. // Geometries
  103262. serializationObject.geometries = {};
  103263. serializationObject.geometries.boxes = [];
  103264. serializationObject.geometries.spheres = [];
  103265. serializationObject.geometries.cylinders = [];
  103266. serializationObject.geometries.toruses = [];
  103267. serializationObject.geometries.grounds = [];
  103268. serializationObject.geometries.planes = [];
  103269. serializationObject.geometries.torusKnots = [];
  103270. serializationObject.geometries.vertexData = [];
  103271. serializedGeometries = [];
  103272. var geometries = scene.getGeometries();
  103273. for (index = 0; index < geometries.length; index++) {
  103274. var geometry = geometries[index];
  103275. if (geometry.isReady()) {
  103276. serializeGeometry(geometry, serializationObject.geometries);
  103277. }
  103278. }
  103279. // Meshes
  103280. serializationObject.meshes = [];
  103281. for (index = 0; index < scene.meshes.length; index++) {
  103282. var abstractMesh = scene.meshes[index];
  103283. if (abstractMesh instanceof BABYLON.Mesh) {
  103284. var mesh = abstractMesh;
  103285. if (!mesh.doNotSerialize) {
  103286. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  103287. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  103288. }
  103289. }
  103290. }
  103291. }
  103292. // Particles Systems
  103293. serializationObject.particleSystems = [];
  103294. for (index = 0; index < scene.particleSystems.length; index++) {
  103295. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  103296. }
  103297. // Action Manager
  103298. if (scene.actionManager) {
  103299. serializationObject.actions = scene.actionManager.serialize("scene");
  103300. }
  103301. // Audio
  103302. serializationObject.sounds = [];
  103303. for (index = 0; index < scene.soundTracks.length; index++) {
  103304. var soundtrack = scene.soundTracks[index];
  103305. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  103306. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  103307. }
  103308. }
  103309. // Components
  103310. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  103311. var component = _c[_b];
  103312. component.serialize(serializationObject);
  103313. }
  103314. return serializationObject;
  103315. };
  103316. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  103317. if (withParents === void 0) { withParents = false; }
  103318. if (withChildren === void 0) { withChildren = false; }
  103319. var serializationObject = {};
  103320. SceneSerializer.ClearCache();
  103321. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  103322. if (withParents || withChildren) {
  103323. //deliberate for loop! not for each, appended should be processed as well.
  103324. for (var i = 0; i < toSerialize.length; ++i) {
  103325. if (withChildren) {
  103326. toSerialize[i].getDescendants().forEach(function (node) {
  103327. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  103328. toSerialize.push(node);
  103329. }
  103330. });
  103331. }
  103332. //make sure the array doesn't contain the object already
  103333. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  103334. toSerialize.push(toSerialize[i].parent);
  103335. }
  103336. }
  103337. }
  103338. toSerialize.forEach(function (mesh) {
  103339. finalizeSingleMesh(mesh, serializationObject);
  103340. });
  103341. return serializationObject;
  103342. };
  103343. return SceneSerializer;
  103344. }());
  103345. BABYLON.SceneSerializer = SceneSerializer;
  103346. })(BABYLON || (BABYLON = {}));
  103347. //# sourceMappingURL=babylon.sceneSerializer.js.map
  103348. var BABYLON;
  103349. (function (BABYLON) {
  103350. /**
  103351. * Class used to generate realtime reflection / refraction cube textures
  103352. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  103353. */
  103354. var ReflectionProbe = /** @class */ (function () {
  103355. /**
  103356. * Creates a new reflection probe
  103357. * @param name defines the name of the probe
  103358. * @param size defines the texture resolution (for each face)
  103359. * @param scene defines the hosting scene
  103360. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  103361. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  103362. */
  103363. function ReflectionProbe(
  103364. /** defines the name of the probe */
  103365. name, size, scene, generateMipMaps, useFloat) {
  103366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  103367. if (useFloat === void 0) { useFloat = false; }
  103368. var _this = this;
  103369. this.name = name;
  103370. this._viewMatrix = BABYLON.Matrix.Identity();
  103371. this._target = BABYLON.Vector3.Zero();
  103372. this._add = BABYLON.Vector3.Zero();
  103373. this._invertYAxis = false;
  103374. /** Gets or sets probe position (center of the cube map) */
  103375. this.position = BABYLON.Vector3.Zero();
  103376. this._scene = scene;
  103377. this._scene.reflectionProbes.push(this);
  103378. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  103379. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  103380. switch (faceIndex) {
  103381. case 0:
  103382. _this._add.copyFromFloats(1, 0, 0);
  103383. break;
  103384. case 1:
  103385. _this._add.copyFromFloats(-1, 0, 0);
  103386. break;
  103387. case 2:
  103388. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  103389. break;
  103390. case 3:
  103391. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  103392. break;
  103393. case 4:
  103394. _this._add.copyFromFloats(0, 0, 1);
  103395. break;
  103396. case 5:
  103397. _this._add.copyFromFloats(0, 0, -1);
  103398. break;
  103399. }
  103400. if (_this._attachedMesh) {
  103401. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  103402. }
  103403. _this.position.addToRef(_this._add, _this._target);
  103404. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  103405. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  103406. scene._forcedViewPosition = _this.position;
  103407. });
  103408. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  103409. scene._forcedViewPosition = null;
  103410. scene.updateTransformMatrix(true);
  103411. });
  103412. if (scene.activeCamera) {
  103413. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  103414. }
  103415. }
  103416. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  103417. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  103418. get: function () {
  103419. return this._renderTargetTexture.samples;
  103420. },
  103421. set: function (value) {
  103422. this._renderTargetTexture.samples = value;
  103423. },
  103424. enumerable: true,
  103425. configurable: true
  103426. });
  103427. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  103428. /** Gets or sets the refresh rate to use (on every frame by default) */
  103429. get: function () {
  103430. return this._renderTargetTexture.refreshRate;
  103431. },
  103432. set: function (value) {
  103433. this._renderTargetTexture.refreshRate = value;
  103434. },
  103435. enumerable: true,
  103436. configurable: true
  103437. });
  103438. /**
  103439. * Gets the hosting scene
  103440. * @returns a Scene
  103441. */
  103442. ReflectionProbe.prototype.getScene = function () {
  103443. return this._scene;
  103444. };
  103445. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  103446. /** Gets the internal CubeTexture used to render to */
  103447. get: function () {
  103448. return this._renderTargetTexture;
  103449. },
  103450. enumerable: true,
  103451. configurable: true
  103452. });
  103453. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  103454. /** Gets the list of meshes to render */
  103455. get: function () {
  103456. return this._renderTargetTexture.renderList;
  103457. },
  103458. enumerable: true,
  103459. configurable: true
  103460. });
  103461. /**
  103462. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  103463. * @param mesh defines the mesh to attach to
  103464. */
  103465. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  103466. this._attachedMesh = mesh;
  103467. };
  103468. /**
  103469. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  103470. * @param renderingGroupId The rendering group id corresponding to its index
  103471. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  103472. */
  103473. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  103474. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  103475. };
  103476. /**
  103477. * Clean all associated resources
  103478. */
  103479. ReflectionProbe.prototype.dispose = function () {
  103480. var index = this._scene.reflectionProbes.indexOf(this);
  103481. if (index !== -1) {
  103482. // Remove from the scene if found
  103483. this._scene.reflectionProbes.splice(index, 1);
  103484. }
  103485. if (this._renderTargetTexture) {
  103486. this._renderTargetTexture.dispose();
  103487. this._renderTargetTexture = null;
  103488. }
  103489. };
  103490. return ReflectionProbe;
  103491. }());
  103492. BABYLON.ReflectionProbe = ReflectionProbe;
  103493. })(BABYLON || (BABYLON = {}));
  103494. //# sourceMappingURL=babylon.reflectionProbe.js.map
  103495. var BABYLON;
  103496. (function (BABYLON) {
  103497. /**
  103498. * Defines the layer scene component responsible to manage any layers
  103499. * in a given scene.
  103500. */
  103501. var LayerSceneComponent = /** @class */ (function () {
  103502. /**
  103503. * Creates a new instance of the component for the given scene
  103504. * @param scene Defines the scene to register the component in
  103505. */
  103506. function LayerSceneComponent(scene) {
  103507. /**
  103508. * The component name helpfull to identify the component in the list of scene components.
  103509. */
  103510. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  103511. this.scene = scene;
  103512. this._engine = scene.getEngine();
  103513. scene.layers = new Array();
  103514. }
  103515. /**
  103516. * Registers the component in a given scene
  103517. */
  103518. LayerSceneComponent.prototype.register = function () {
  103519. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  103520. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  103521. };
  103522. /**
  103523. * Rebuilds the elements related to this component in case of
  103524. * context lost for instance.
  103525. */
  103526. LayerSceneComponent.prototype.rebuild = function () {
  103527. var layers = this.scene.layers;
  103528. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  103529. var layer = layers_1[_i];
  103530. layer._rebuild();
  103531. }
  103532. };
  103533. /**
  103534. * Disposes the component and the associated ressources.
  103535. */
  103536. LayerSceneComponent.prototype.dispose = function () {
  103537. var layers = this.scene.layers;
  103538. while (layers.length) {
  103539. layers[0].dispose();
  103540. }
  103541. };
  103542. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  103543. var layers = this.scene.layers;
  103544. if (layers.length) {
  103545. this._engine.setDepthBuffer(false);
  103546. var cameraLayerMask = camera.layerMask;
  103547. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  103548. var layer = layers_2[_i];
  103549. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  103550. layer.render();
  103551. }
  103552. }
  103553. this._engine.setDepthBuffer(true);
  103554. }
  103555. };
  103556. LayerSceneComponent.prototype._drawBackground = function (camera) {
  103557. this._draw(camera, true);
  103558. };
  103559. LayerSceneComponent.prototype._drawForeground = function (camera) {
  103560. this._draw(camera, false);
  103561. };
  103562. return LayerSceneComponent;
  103563. }());
  103564. BABYLON.LayerSceneComponent = LayerSceneComponent;
  103565. })(BABYLON || (BABYLON = {}));
  103566. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  103567. var BABYLON;
  103568. (function (BABYLON) {
  103569. var Layer = /** @class */ (function () {
  103570. function Layer(name, imgUrl, scene, isBackground, color) {
  103571. this.name = name;
  103572. this.scale = new BABYLON.Vector2(1, 1);
  103573. this.offset = new BABYLON.Vector2(0, 0);
  103574. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  103575. this.layerMask = 0x0FFFFFFF;
  103576. this._vertexBuffers = {};
  103577. // Events
  103578. /**
  103579. * An event triggered when the layer is disposed.
  103580. */
  103581. this.onDisposeObservable = new BABYLON.Observable();
  103582. /**
  103583. * An event triggered before rendering the scene
  103584. */
  103585. this.onBeforeRenderObservable = new BABYLON.Observable();
  103586. /**
  103587. * An event triggered after rendering the scene
  103588. */
  103589. this.onAfterRenderObservable = new BABYLON.Observable();
  103590. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  103591. this.isBackground = isBackground === undefined ? true : isBackground;
  103592. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  103593. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  103594. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  103595. if (!layerComponent) {
  103596. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  103597. this._scene._addComponent(layerComponent);
  103598. }
  103599. this._scene.layers.push(this);
  103600. var engine = this._scene.getEngine();
  103601. // VBO
  103602. var vertices = [];
  103603. vertices.push(1, 1);
  103604. vertices.push(-1, 1);
  103605. vertices.push(-1, -1);
  103606. vertices.push(1, -1);
  103607. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  103608. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  103609. this._createIndexBuffer();
  103610. // Effects
  103611. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  103612. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  103613. }
  103614. Object.defineProperty(Layer.prototype, "onDispose", {
  103615. set: function (callback) {
  103616. if (this._onDisposeObserver) {
  103617. this.onDisposeObservable.remove(this._onDisposeObserver);
  103618. }
  103619. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  103620. },
  103621. enumerable: true,
  103622. configurable: true
  103623. });
  103624. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  103625. set: function (callback) {
  103626. if (this._onBeforeRenderObserver) {
  103627. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  103628. }
  103629. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  103630. },
  103631. enumerable: true,
  103632. configurable: true
  103633. });
  103634. Object.defineProperty(Layer.prototype, "onAfterRender", {
  103635. set: function (callback) {
  103636. if (this._onAfterRenderObserver) {
  103637. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  103638. }
  103639. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  103640. },
  103641. enumerable: true,
  103642. configurable: true
  103643. });
  103644. Layer.prototype._createIndexBuffer = function () {
  103645. var engine = this._scene.getEngine();
  103646. // Indices
  103647. var indices = [];
  103648. indices.push(0);
  103649. indices.push(1);
  103650. indices.push(2);
  103651. indices.push(0);
  103652. indices.push(2);
  103653. indices.push(3);
  103654. this._indexBuffer = engine.createIndexBuffer(indices);
  103655. };
  103656. /** @hidden */
  103657. Layer.prototype._rebuild = function () {
  103658. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103659. if (vb) {
  103660. vb._rebuild();
  103661. }
  103662. this._createIndexBuffer();
  103663. };
  103664. Layer.prototype.render = function () {
  103665. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  103666. // Check
  103667. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  103668. return;
  103669. var engine = this._scene.getEngine();
  103670. this.onBeforeRenderObservable.notifyObservers(this);
  103671. // Render
  103672. engine.enableEffect(currentEffect);
  103673. engine.setState(false);
  103674. // Texture
  103675. currentEffect.setTexture("textureSampler", this.texture);
  103676. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  103677. // Color
  103678. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  103679. // Scale / offset
  103680. currentEffect.setVector2("offset", this.offset);
  103681. currentEffect.setVector2("scale", this.scale);
  103682. // VBOs
  103683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  103684. // Draw order
  103685. if (!this.alphaTest) {
  103686. engine.setAlphaMode(this.alphaBlendingMode);
  103687. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103688. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103689. }
  103690. else {
  103691. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103692. }
  103693. this.onAfterRenderObservable.notifyObservers(this);
  103694. };
  103695. Layer.prototype.dispose = function () {
  103696. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103697. if (vertexBuffer) {
  103698. vertexBuffer.dispose();
  103699. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  103700. }
  103701. if (this._indexBuffer) {
  103702. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  103703. this._indexBuffer = null;
  103704. }
  103705. if (this.texture) {
  103706. this.texture.dispose();
  103707. this.texture = null;
  103708. }
  103709. // Remove from scene
  103710. var index = this._scene.layers.indexOf(this);
  103711. this._scene.layers.splice(index, 1);
  103712. // Callback
  103713. this.onDisposeObservable.notifyObservers(this);
  103714. this.onDisposeObservable.clear();
  103715. this.onAfterRenderObservable.clear();
  103716. this.onBeforeRenderObservable.clear();
  103717. };
  103718. return Layer;
  103719. }());
  103720. BABYLON.Layer = Layer;
  103721. })(BABYLON || (BABYLON = {}));
  103722. //# sourceMappingURL=babylon.layer.js.map
  103723. var BABYLON;
  103724. (function (BABYLON) {
  103725. var TextureTools = /** @class */ (function () {
  103726. function TextureTools() {
  103727. }
  103728. /**
  103729. * Uses the GPU to create a copy texture rescaled at a given size
  103730. * @param texture Texture to copy from
  103731. * @param width Desired width
  103732. * @param height Desired height
  103733. * @return Generated texture
  103734. */
  103735. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  103736. if (useBilinearMode === void 0) { useBilinearMode = true; }
  103737. var scene = texture.getScene();
  103738. var engine = scene.getEngine();
  103739. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  103740. rtt.wrapU = texture.wrapU;
  103741. rtt.wrapV = texture.wrapV;
  103742. rtt.uOffset = texture.uOffset;
  103743. rtt.vOffset = texture.vOffset;
  103744. rtt.uScale = texture.uScale;
  103745. rtt.vScale = texture.vScale;
  103746. rtt.uAng = texture.uAng;
  103747. rtt.vAng = texture.vAng;
  103748. rtt.wAng = texture.wAng;
  103749. rtt.coordinatesIndex = texture.coordinatesIndex;
  103750. rtt.level = texture.level;
  103751. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  103752. rtt._texture.isReady = false;
  103753. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103754. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103755. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  103756. passPostProcess.getEffect().executeWhenCompiled(function () {
  103757. passPostProcess.onApply = function (effect) {
  103758. effect.setTexture("textureSampler", texture);
  103759. };
  103760. var internalTexture = rtt.getInternalTexture();
  103761. if (internalTexture) {
  103762. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  103763. engine.unBindFramebuffer(internalTexture);
  103764. rtt.disposeFramebufferObjects();
  103765. passPostProcess.dispose();
  103766. internalTexture.isReady = true;
  103767. }
  103768. });
  103769. return rtt;
  103770. };
  103771. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  103772. if (!scene._environmentBRDFTexture) {
  103773. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103774. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103775. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103776. scene._environmentBRDFTexture = texture;
  103777. }
  103778. return scene._environmentBRDFTexture;
  103779. };
  103780. 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=";
  103781. return TextureTools;
  103782. }());
  103783. BABYLON.TextureTools = TextureTools;
  103784. })(BABYLON || (BABYLON = {}));
  103785. //# sourceMappingURL=babylon.textureTools.js.map
  103786. var BABYLON;
  103787. (function (BABYLON) {
  103788. var FramingBehavior = /** @class */ (function () {
  103789. function FramingBehavior() {
  103790. this._mode = FramingBehavior.FitFrustumSidesMode;
  103791. this._radiusScale = 1.0;
  103792. this._positionScale = 0.5;
  103793. this._defaultElevation = 0.3;
  103794. this._elevationReturnTime = 1500;
  103795. this._elevationReturnWaitTime = 1000;
  103796. this._zoomStopsAnimation = false;
  103797. this._framingTime = 1500;
  103798. this._isPointerDown = false;
  103799. this._lastInteractionTime = -Infinity;
  103800. // Framing control
  103801. this._animatables = new Array();
  103802. this._betaIsAnimating = false;
  103803. }
  103804. Object.defineProperty(FramingBehavior.prototype, "name", {
  103805. get: function () {
  103806. return "Framing";
  103807. },
  103808. enumerable: true,
  103809. configurable: true
  103810. });
  103811. Object.defineProperty(FramingBehavior.prototype, "mode", {
  103812. /**
  103813. * Gets current mode used by the behavior.
  103814. */
  103815. get: function () {
  103816. return this._mode;
  103817. },
  103818. /**
  103819. * Sets the current mode used by the behavior
  103820. */
  103821. set: function (mode) {
  103822. this._mode = mode;
  103823. },
  103824. enumerable: true,
  103825. configurable: true
  103826. });
  103827. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  103828. /**
  103829. * Gets the scale applied to the radius
  103830. */
  103831. get: function () {
  103832. return this._radiusScale;
  103833. },
  103834. /**
  103835. * Sets the scale applied to the radius (1 by default)
  103836. */
  103837. set: function (radius) {
  103838. this._radiusScale = radius;
  103839. },
  103840. enumerable: true,
  103841. configurable: true
  103842. });
  103843. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  103844. /**
  103845. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103846. */
  103847. get: function () {
  103848. return this._positionScale;
  103849. },
  103850. /**
  103851. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103852. */
  103853. set: function (scale) {
  103854. this._positionScale = scale;
  103855. },
  103856. enumerable: true,
  103857. configurable: true
  103858. });
  103859. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  103860. /**
  103861. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103862. * behaviour is triggered, in radians.
  103863. */
  103864. get: function () {
  103865. return this._defaultElevation;
  103866. },
  103867. /**
  103868. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103869. * behaviour is triggered, in radians.
  103870. */
  103871. set: function (elevation) {
  103872. this._defaultElevation = elevation;
  103873. },
  103874. enumerable: true,
  103875. configurable: true
  103876. });
  103877. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  103878. /**
  103879. * Gets the time (in milliseconds) taken to return to the default beta position.
  103880. * Negative value indicates camera should not return to default.
  103881. */
  103882. get: function () {
  103883. return this._elevationReturnTime;
  103884. },
  103885. /**
  103886. * Sets the time (in milliseconds) taken to return to the default beta position.
  103887. * Negative value indicates camera should not return to default.
  103888. */
  103889. set: function (speed) {
  103890. this._elevationReturnTime = speed;
  103891. },
  103892. enumerable: true,
  103893. configurable: true
  103894. });
  103895. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  103896. /**
  103897. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103898. */
  103899. get: function () {
  103900. return this._elevationReturnWaitTime;
  103901. },
  103902. /**
  103903. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103904. */
  103905. set: function (time) {
  103906. this._elevationReturnWaitTime = time;
  103907. },
  103908. enumerable: true,
  103909. configurable: true
  103910. });
  103911. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  103912. /**
  103913. * Gets the flag that indicates if user zooming should stop animation.
  103914. */
  103915. get: function () {
  103916. return this._zoomStopsAnimation;
  103917. },
  103918. /**
  103919. * Sets the flag that indicates if user zooming should stop animation.
  103920. */
  103921. set: function (flag) {
  103922. this._zoomStopsAnimation = flag;
  103923. },
  103924. enumerable: true,
  103925. configurable: true
  103926. });
  103927. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  103928. /**
  103929. * Gets the transition time when framing the mesh, in milliseconds
  103930. */
  103931. get: function () {
  103932. return this._framingTime;
  103933. },
  103934. /**
  103935. * Sets the transition time when framing the mesh, in milliseconds
  103936. */
  103937. set: function (time) {
  103938. this._framingTime = time;
  103939. },
  103940. enumerable: true,
  103941. configurable: true
  103942. });
  103943. FramingBehavior.prototype.init = function () {
  103944. // Do notihng
  103945. };
  103946. FramingBehavior.prototype.attach = function (camera) {
  103947. var _this = this;
  103948. this._attachedCamera = camera;
  103949. var scene = this._attachedCamera.getScene();
  103950. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  103951. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103952. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103953. _this._isPointerDown = true;
  103954. return;
  103955. }
  103956. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103957. _this._isPointerDown = false;
  103958. }
  103959. });
  103960. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103961. if (mesh) {
  103962. _this.zoomOnMesh(mesh);
  103963. }
  103964. });
  103965. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103966. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103967. _this._applyUserInteraction();
  103968. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  103969. // back to the default position after a given timeout
  103970. _this._maintainCameraAboveGround();
  103971. });
  103972. };
  103973. FramingBehavior.prototype.detach = function () {
  103974. if (!this._attachedCamera) {
  103975. return;
  103976. }
  103977. var scene = this._attachedCamera.getScene();
  103978. if (this._onPrePointerObservableObserver) {
  103979. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103980. }
  103981. if (this._onAfterCheckInputsObserver) {
  103982. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103983. }
  103984. if (this._onMeshTargetChangedObserver) {
  103985. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103986. }
  103987. this._attachedCamera = null;
  103988. };
  103989. /**
  103990. * Targets the given mesh and updates zoom level accordingly.
  103991. * @param mesh The mesh to target.
  103992. * @param radius Optional. If a cached radius position already exists, overrides default.
  103993. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103994. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103995. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103996. */
  103997. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103998. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103999. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104000. mesh.computeWorldMatrix(true);
  104001. var boundingBox = mesh.getBoundingInfo().boundingBox;
  104002. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  104003. };
  104004. /**
  104005. * Targets the given mesh with its children and updates zoom level accordingly.
  104006. * @param mesh The mesh to target.
  104007. * @param radius Optional. If a cached radius position already exists, overrides default.
  104008. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104009. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104010. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104011. */
  104012. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104013. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104014. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104015. mesh.computeWorldMatrix(true);
  104016. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  104017. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  104018. };
  104019. /**
  104020. * Targets the given meshes with their children and updates zoom level accordingly.
  104021. * @param meshes The mesh to target.
  104022. * @param radius Optional. If a cached radius position already exists, overrides default.
  104023. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104024. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104025. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104026. */
  104027. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  104028. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104029. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104030. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  104031. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  104032. for (var i = 0; i < meshes.length; i++) {
  104033. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  104034. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  104035. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  104036. }
  104037. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  104038. };
  104039. /**
  104040. * Targets the given mesh and updates zoom level accordingly.
  104041. * @param mesh The mesh to target.
  104042. * @param radius Optional. If a cached radius position already exists, overrides default.
  104043. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104044. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104045. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104046. */
  104047. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  104048. var _this = this;
  104049. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104050. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104051. var zoomTarget;
  104052. if (!this._attachedCamera) {
  104053. return;
  104054. }
  104055. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  104056. var bottom = minimumWorld.y;
  104057. var top = maximumWorld.y;
  104058. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  104059. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  104060. if (focusOnOriginXZ) {
  104061. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  104062. }
  104063. else {
  104064. var centerWorld = minimumWorld.add(radiusWorld);
  104065. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  104066. }
  104067. if (!this._vectorTransition) {
  104068. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  104069. }
  104070. this._betaIsAnimating = true;
  104071. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  104072. if (animatable) {
  104073. this._animatables.push(animatable);
  104074. }
  104075. // sets the radius and lower radius bounds
  104076. // Small delta ensures camera is not always at lower zoom limit.
  104077. var radius = 0;
  104078. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  104079. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104080. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  104081. radius = position;
  104082. }
  104083. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104084. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104085. if (this._attachedCamera.lowerRadiusLimit === null) {
  104086. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  104087. }
  104088. }
  104089. // Set sensibilities
  104090. var extend = maximumWorld.subtract(minimumWorld).length();
  104091. this._attachedCamera.panningSensibility = 5000 / extend;
  104092. this._attachedCamera.wheelPrecision = 100 / radius;
  104093. // transition to new radius
  104094. if (!this._radiusTransition) {
  104095. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  104096. }
  104097. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  104098. _this.stopAllAnimations();
  104099. if (onAnimationEnd) {
  104100. onAnimationEnd();
  104101. }
  104102. if (_this._attachedCamera) {
  104103. _this._attachedCamera.storeState();
  104104. }
  104105. });
  104106. if (animatable) {
  104107. this._animatables.push(animatable);
  104108. }
  104109. };
  104110. /**
  104111. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  104112. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  104113. * frustum width.
  104114. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  104115. * to fully enclose the mesh in the viewing frustum.
  104116. */
  104117. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  104118. var size = maximumWorld.subtract(minimumWorld);
  104119. var boxVectorGlobalDiagonal = size.length();
  104120. var frustumSlope = this._getFrustumSlope();
  104121. // Formula for setting distance
  104122. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  104123. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  104124. // Horizon distance
  104125. var radius = radiusWithoutFraming * this._radiusScale;
  104126. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  104127. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  104128. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  104129. var camera = this._attachedCamera;
  104130. if (!camera) {
  104131. return 0;
  104132. }
  104133. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104134. // Don't exceed the requested limit
  104135. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  104136. }
  104137. // Don't exceed the upper radius limit
  104138. if (camera.upperRadiusLimit) {
  104139. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  104140. }
  104141. return distance;
  104142. };
  104143. /**
  104144. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  104145. * is automatically returned to its default position (expected to be above ground plane).
  104146. */
  104147. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  104148. var _this = this;
  104149. if (this._elevationReturnTime < 0) {
  104150. return;
  104151. }
  104152. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  104153. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  104154. var limitBeta = Math.PI * 0.5;
  104155. // Bring the camera back up if below the ground plane
  104156. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  104157. this._betaIsAnimating = true;
  104158. //Transition to new position
  104159. this.stopAllAnimations();
  104160. if (!this._betaTransition) {
  104161. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  104162. }
  104163. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  104164. _this._clearAnimationLocks();
  104165. _this.stopAllAnimations();
  104166. });
  104167. if (animatabe) {
  104168. this._animatables.push(animatabe);
  104169. }
  104170. }
  104171. };
  104172. /**
  104173. * Returns the frustum slope based on the canvas ratio and camera FOV
  104174. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  104175. */
  104176. FramingBehavior.prototype._getFrustumSlope = function () {
  104177. // Calculate the viewport ratio
  104178. // Aspect Ratio is Height/Width.
  104179. var camera = this._attachedCamera;
  104180. if (!camera) {
  104181. return BABYLON.Vector2.Zero();
  104182. }
  104183. var engine = camera.getScene().getEngine();
  104184. var aspectRatio = engine.getAspectRatio(camera);
  104185. // Camera FOV is the vertical field of view (top-bottom) in radians.
  104186. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  104187. var frustumSlopeY = Math.tan(camera.fov / 2);
  104188. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  104189. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  104190. // along the forward vector.
  104191. var frustumSlopeX = frustumSlopeY * aspectRatio;
  104192. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  104193. };
  104194. /**
  104195. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  104196. */
  104197. FramingBehavior.prototype._clearAnimationLocks = function () {
  104198. this._betaIsAnimating = false;
  104199. };
  104200. /**
  104201. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  104202. */
  104203. FramingBehavior.prototype._applyUserInteraction = function () {
  104204. if (this.isUserIsMoving) {
  104205. this._lastInteractionTime = BABYLON.Tools.Now;
  104206. this.stopAllAnimations();
  104207. this._clearAnimationLocks();
  104208. }
  104209. };
  104210. /**
  104211. * Stops and removes all animations that have been applied to the camera
  104212. */
  104213. FramingBehavior.prototype.stopAllAnimations = function () {
  104214. if (this._attachedCamera) {
  104215. this._attachedCamera.animations = [];
  104216. }
  104217. while (this._animatables.length) {
  104218. if (this._animatables[0]) {
  104219. this._animatables[0].onAnimationEnd = null;
  104220. this._animatables[0].stop();
  104221. }
  104222. this._animatables.shift();
  104223. }
  104224. };
  104225. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  104226. /**
  104227. * Gets a value indicating if the user is moving the camera
  104228. */
  104229. get: function () {
  104230. if (!this._attachedCamera) {
  104231. return false;
  104232. }
  104233. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  104234. this._attachedCamera.inertialBetaOffset !== 0 ||
  104235. this._attachedCamera.inertialRadiusOffset !== 0 ||
  104236. this._attachedCamera.inertialPanningX !== 0 ||
  104237. this._attachedCamera.inertialPanningY !== 0 ||
  104238. this._isPointerDown;
  104239. },
  104240. enumerable: true,
  104241. configurable: true
  104242. });
  104243. /**
  104244. * The easing function used by animations
  104245. */
  104246. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  104247. /**
  104248. * The easing mode used by animations
  104249. */
  104250. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  104251. // Statics
  104252. /**
  104253. * The camera can move all the way towards the mesh.
  104254. */
  104255. FramingBehavior.IgnoreBoundsSizeMode = 0;
  104256. /**
  104257. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  104258. */
  104259. FramingBehavior.FitFrustumSidesMode = 1;
  104260. return FramingBehavior;
  104261. }());
  104262. BABYLON.FramingBehavior = FramingBehavior;
  104263. })(BABYLON || (BABYLON = {}));
  104264. //# sourceMappingURL=babylon.framingBehavior.js.map
  104265. var BABYLON;
  104266. (function (BABYLON) {
  104267. /**
  104268. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  104269. */
  104270. var BouncingBehavior = /** @class */ (function () {
  104271. function BouncingBehavior() {
  104272. /**
  104273. * The duration of the animation, in milliseconds
  104274. */
  104275. this.transitionDuration = 450;
  104276. /**
  104277. * Length of the distance animated by the transition when lower radius is reached
  104278. */
  104279. this.lowerRadiusTransitionRange = 2;
  104280. /**
  104281. * Length of the distance animated by the transition when upper radius is reached
  104282. */
  104283. this.upperRadiusTransitionRange = -2;
  104284. this._autoTransitionRange = false;
  104285. // Animations
  104286. this._radiusIsAnimating = false;
  104287. this._radiusBounceTransition = null;
  104288. this._animatables = new Array();
  104289. }
  104290. Object.defineProperty(BouncingBehavior.prototype, "name", {
  104291. get: function () {
  104292. return "Bouncing";
  104293. },
  104294. enumerable: true,
  104295. configurable: true
  104296. });
  104297. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  104298. /**
  104299. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  104300. */
  104301. get: function () {
  104302. return this._autoTransitionRange;
  104303. },
  104304. /**
  104305. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  104306. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  104307. */
  104308. set: function (value) {
  104309. var _this = this;
  104310. if (this._autoTransitionRange === value) {
  104311. return;
  104312. }
  104313. this._autoTransitionRange = value;
  104314. var camera = this._attachedCamera;
  104315. if (!camera) {
  104316. return;
  104317. }
  104318. if (value) {
  104319. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104320. if (!mesh) {
  104321. return;
  104322. }
  104323. mesh.computeWorldMatrix(true);
  104324. var diagonal = mesh.getBoundingInfo().diagonalLength;
  104325. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  104326. _this.upperRadiusTransitionRange = diagonal * 0.05;
  104327. });
  104328. }
  104329. else if (this._onMeshTargetChangedObserver) {
  104330. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104331. }
  104332. },
  104333. enumerable: true,
  104334. configurable: true
  104335. });
  104336. BouncingBehavior.prototype.init = function () {
  104337. // Do notihng
  104338. };
  104339. BouncingBehavior.prototype.attach = function (camera) {
  104340. var _this = this;
  104341. this._attachedCamera = camera;
  104342. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104343. if (!_this._attachedCamera) {
  104344. return;
  104345. }
  104346. // Add the bounce animation to the lower radius limit
  104347. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  104348. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  104349. }
  104350. // Add the bounce animation to the upper radius limit
  104351. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  104352. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  104353. }
  104354. });
  104355. };
  104356. BouncingBehavior.prototype.detach = function () {
  104357. if (!this._attachedCamera) {
  104358. return;
  104359. }
  104360. if (this._onAfterCheckInputsObserver) {
  104361. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104362. }
  104363. if (this._onMeshTargetChangedObserver) {
  104364. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104365. }
  104366. this._attachedCamera = null;
  104367. };
  104368. /**
  104369. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  104370. * @param radiusLimit The limit to check against.
  104371. * @return Bool to indicate if at limit.
  104372. */
  104373. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  104374. if (!this._attachedCamera) {
  104375. return false;
  104376. }
  104377. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  104378. return true;
  104379. }
  104380. return false;
  104381. };
  104382. /**
  104383. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  104384. * @param radiusDelta The delta by which to animate to. Can be negative.
  104385. */
  104386. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  104387. var _this = this;
  104388. if (!this._attachedCamera) {
  104389. return;
  104390. }
  104391. if (!this._radiusBounceTransition) {
  104392. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  104393. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  104394. }
  104395. // Prevent zoom until bounce has completed
  104396. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  104397. this._attachedCamera.wheelPrecision = Infinity;
  104398. this._attachedCamera.inertialRadiusOffset = 0;
  104399. // Animate to the radius limit
  104400. this.stopAllAnimations();
  104401. this._radiusIsAnimating = true;
  104402. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  104403. if (animatable) {
  104404. this._animatables.push(animatable);
  104405. }
  104406. };
  104407. /**
  104408. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  104409. */
  104410. BouncingBehavior.prototype._clearAnimationLocks = function () {
  104411. this._radiusIsAnimating = false;
  104412. if (this._attachedCamera) {
  104413. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  104414. }
  104415. };
  104416. /**
  104417. * Stops and removes all animations that have been applied to the camera
  104418. */
  104419. BouncingBehavior.prototype.stopAllAnimations = function () {
  104420. if (this._attachedCamera) {
  104421. this._attachedCamera.animations = [];
  104422. }
  104423. while (this._animatables.length) {
  104424. this._animatables[0].onAnimationEnd = null;
  104425. this._animatables[0].stop();
  104426. this._animatables.shift();
  104427. }
  104428. };
  104429. /**
  104430. * The easing function used by animations
  104431. */
  104432. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  104433. /**
  104434. * The easing mode used by animations
  104435. */
  104436. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  104437. return BouncingBehavior;
  104438. }());
  104439. BABYLON.BouncingBehavior = BouncingBehavior;
  104440. })(BABYLON || (BABYLON = {}));
  104441. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  104442. var BABYLON;
  104443. (function (BABYLON) {
  104444. var AutoRotationBehavior = /** @class */ (function () {
  104445. function AutoRotationBehavior() {
  104446. this._zoomStopsAnimation = false;
  104447. this._idleRotationSpeed = 0.05;
  104448. this._idleRotationWaitTime = 2000;
  104449. this._idleRotationSpinupTime = 2000;
  104450. this._isPointerDown = false;
  104451. this._lastFrameTime = null;
  104452. this._lastInteractionTime = -Infinity;
  104453. this._cameraRotationSpeed = 0;
  104454. this._lastFrameRadius = 0;
  104455. }
  104456. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  104457. get: function () {
  104458. return "AutoRotation";
  104459. },
  104460. enumerable: true,
  104461. configurable: true
  104462. });
  104463. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  104464. /**
  104465. * Gets the flag that indicates if user zooming should stop animation.
  104466. */
  104467. get: function () {
  104468. return this._zoomStopsAnimation;
  104469. },
  104470. /**
  104471. * Sets the flag that indicates if user zooming should stop animation.
  104472. */
  104473. set: function (flag) {
  104474. this._zoomStopsAnimation = flag;
  104475. },
  104476. enumerable: true,
  104477. configurable: true
  104478. });
  104479. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  104480. /**
  104481. * Gets the default speed at which the camera rotates around the model.
  104482. */
  104483. get: function () {
  104484. return this._idleRotationSpeed;
  104485. },
  104486. /**
  104487. * Sets the default speed at which the camera rotates around the model.
  104488. */
  104489. set: function (speed) {
  104490. this._idleRotationSpeed = speed;
  104491. },
  104492. enumerable: true,
  104493. configurable: true
  104494. });
  104495. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  104496. /**
  104497. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  104498. */
  104499. get: function () {
  104500. return this._idleRotationWaitTime;
  104501. },
  104502. /**
  104503. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  104504. */
  104505. set: function (time) {
  104506. this._idleRotationWaitTime = time;
  104507. },
  104508. enumerable: true,
  104509. configurable: true
  104510. });
  104511. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  104512. /**
  104513. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  104514. */
  104515. get: function () {
  104516. return this._idleRotationSpinupTime;
  104517. },
  104518. /**
  104519. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  104520. */
  104521. set: function (time) {
  104522. this._idleRotationSpinupTime = time;
  104523. },
  104524. enumerable: true,
  104525. configurable: true
  104526. });
  104527. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  104528. /**
  104529. * Gets a value indicating if the camera is currently rotating because of this behavior
  104530. */
  104531. get: function () {
  104532. return Math.abs(this._cameraRotationSpeed) > 0;
  104533. },
  104534. enumerable: true,
  104535. configurable: true
  104536. });
  104537. AutoRotationBehavior.prototype.init = function () {
  104538. // Do notihng
  104539. };
  104540. AutoRotationBehavior.prototype.attach = function (camera) {
  104541. var _this = this;
  104542. this._attachedCamera = camera;
  104543. var scene = this._attachedCamera.getScene();
  104544. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104545. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104546. _this._isPointerDown = true;
  104547. return;
  104548. }
  104549. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104550. _this._isPointerDown = false;
  104551. }
  104552. });
  104553. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104554. var now = BABYLON.Tools.Now;
  104555. var dt = 0;
  104556. if (_this._lastFrameTime != null) {
  104557. dt = now - _this._lastFrameTime;
  104558. }
  104559. _this._lastFrameTime = now;
  104560. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104561. _this._applyUserInteraction();
  104562. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  104563. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  104564. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  104565. // Step camera rotation by rotation speed
  104566. if (_this._attachedCamera) {
  104567. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  104568. }
  104569. });
  104570. };
  104571. AutoRotationBehavior.prototype.detach = function () {
  104572. if (!this._attachedCamera) {
  104573. return;
  104574. }
  104575. var scene = this._attachedCamera.getScene();
  104576. if (this._onPrePointerObservableObserver) {
  104577. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104578. }
  104579. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104580. this._attachedCamera = null;
  104581. };
  104582. /**
  104583. * Returns true if user is scrolling.
  104584. * @return true if user is scrolling.
  104585. */
  104586. AutoRotationBehavior.prototype._userIsZooming = function () {
  104587. if (!this._attachedCamera) {
  104588. return false;
  104589. }
  104590. return this._attachedCamera.inertialRadiusOffset !== 0;
  104591. };
  104592. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  104593. if (!this._attachedCamera) {
  104594. return false;
  104595. }
  104596. var zoomHasHitLimit = false;
  104597. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  104598. zoomHasHitLimit = true;
  104599. }
  104600. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  104601. this._lastFrameRadius = this._attachedCamera.radius;
  104602. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  104603. };
  104604. /**
  104605. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  104606. */
  104607. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  104608. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  104609. this._lastInteractionTime = BABYLON.Tools.Now;
  104610. }
  104611. };
  104612. // Tools
  104613. AutoRotationBehavior.prototype._userIsMoving = function () {
  104614. if (!this._attachedCamera) {
  104615. return false;
  104616. }
  104617. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  104618. this._attachedCamera.inertialBetaOffset !== 0 ||
  104619. this._attachedCamera.inertialRadiusOffset !== 0 ||
  104620. this._attachedCamera.inertialPanningX !== 0 ||
  104621. this._attachedCamera.inertialPanningY !== 0 ||
  104622. this._isPointerDown;
  104623. };
  104624. return AutoRotationBehavior;
  104625. }());
  104626. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  104627. })(BABYLON || (BABYLON = {}));
  104628. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  104629. var BABYLON;
  104630. (function (BABYLON) {
  104631. var NullEngineOptions = /** @class */ (function () {
  104632. function NullEngineOptions() {
  104633. this.renderWidth = 512;
  104634. this.renderHeight = 256;
  104635. this.textureSize = 512;
  104636. this.deterministicLockstep = false;
  104637. this.lockstepMaxSteps = 4;
  104638. }
  104639. return NullEngineOptions;
  104640. }());
  104641. BABYLON.NullEngineOptions = NullEngineOptions;
  104642. /**
  104643. * The null engine class provides support for headless version of babylon.js.
  104644. * This can be used in server side scenario or for testing purposes
  104645. */
  104646. var NullEngine = /** @class */ (function (_super) {
  104647. __extends(NullEngine, _super);
  104648. function NullEngine(options) {
  104649. if (options === void 0) { options = new NullEngineOptions(); }
  104650. var _this = _super.call(this, null) || this;
  104651. if (options.deterministicLockstep === undefined) {
  104652. options.deterministicLockstep = false;
  104653. }
  104654. if (options.lockstepMaxSteps === undefined) {
  104655. options.lockstepMaxSteps = 4;
  104656. }
  104657. _this._options = options;
  104658. // Init caps
  104659. // We consider we are on a webgl1 capable device
  104660. _this._caps = new BABYLON.EngineCapabilities();
  104661. _this._caps.maxTexturesImageUnits = 16;
  104662. _this._caps.maxVertexTextureImageUnits = 16;
  104663. _this._caps.maxTextureSize = 512;
  104664. _this._caps.maxCubemapTextureSize = 512;
  104665. _this._caps.maxRenderTextureSize = 512;
  104666. _this._caps.maxVertexAttribs = 16;
  104667. _this._caps.maxVaryingVectors = 16;
  104668. _this._caps.maxFragmentUniformVectors = 16;
  104669. _this._caps.maxVertexUniformVectors = 16;
  104670. // Extensions
  104671. _this._caps.standardDerivatives = false;
  104672. _this._caps.astc = null;
  104673. _this._caps.s3tc = null;
  104674. _this._caps.pvrtc = null;
  104675. _this._caps.etc1 = null;
  104676. _this._caps.etc2 = null;
  104677. _this._caps.textureAnisotropicFilterExtension = null;
  104678. _this._caps.maxAnisotropy = 0;
  104679. _this._caps.uintIndices = false;
  104680. _this._caps.fragmentDepthSupported = false;
  104681. _this._caps.highPrecisionShaderSupported = true;
  104682. _this._caps.colorBufferFloat = false;
  104683. _this._caps.textureFloat = false;
  104684. _this._caps.textureFloatLinearFiltering = false;
  104685. _this._caps.textureFloatRender = false;
  104686. _this._caps.textureHalfFloat = false;
  104687. _this._caps.textureHalfFloatLinearFiltering = false;
  104688. _this._caps.textureHalfFloatRender = false;
  104689. _this._caps.textureLOD = false;
  104690. _this._caps.drawBuffersExtension = false;
  104691. _this._caps.depthTextureExtension = false;
  104692. _this._caps.vertexArrayObject = false;
  104693. _this._caps.instancedArrays = false;
  104694. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  104695. // Wrappers
  104696. if (typeof URL === "undefined") {
  104697. URL = {
  104698. createObjectURL: function () { },
  104699. revokeObjectURL: function () { }
  104700. };
  104701. }
  104702. if (typeof Blob === "undefined") {
  104703. Blob = function () { };
  104704. }
  104705. return _this;
  104706. }
  104707. NullEngine.prototype.isDeterministicLockStep = function () {
  104708. return this._options.deterministicLockstep;
  104709. };
  104710. NullEngine.prototype.getLockstepMaxSteps = function () {
  104711. return this._options.lockstepMaxSteps;
  104712. };
  104713. NullEngine.prototype.getHardwareScalingLevel = function () {
  104714. return 1.0;
  104715. };
  104716. NullEngine.prototype.createVertexBuffer = function (vertices) {
  104717. return {
  104718. capacity: 0,
  104719. references: 1,
  104720. is32Bits: false
  104721. };
  104722. };
  104723. NullEngine.prototype.createIndexBuffer = function (indices) {
  104724. return {
  104725. capacity: 0,
  104726. references: 1,
  104727. is32Bits: false
  104728. };
  104729. };
  104730. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  104731. if (stencil === void 0) { stencil = false; }
  104732. };
  104733. NullEngine.prototype.getRenderWidth = function (useScreen) {
  104734. if (useScreen === void 0) { useScreen = false; }
  104735. if (!useScreen && this._currentRenderTarget) {
  104736. return this._currentRenderTarget.width;
  104737. }
  104738. return this._options.renderWidth;
  104739. };
  104740. NullEngine.prototype.getRenderHeight = function (useScreen) {
  104741. if (useScreen === void 0) { useScreen = false; }
  104742. if (!useScreen && this._currentRenderTarget) {
  104743. return this._currentRenderTarget.height;
  104744. }
  104745. return this._options.renderHeight;
  104746. };
  104747. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  104748. this._cachedViewport = viewport;
  104749. };
  104750. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  104751. return {
  104752. transformFeedback: null,
  104753. __SPECTOR_rebuildProgram: null
  104754. };
  104755. };
  104756. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  104757. return [];
  104758. };
  104759. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  104760. return [];
  104761. };
  104762. NullEngine.prototype.bindSamplers = function (effect) {
  104763. this._currentEffect = null;
  104764. };
  104765. NullEngine.prototype.enableEffect = function (effect) {
  104766. this._currentEffect = effect;
  104767. if (effect.onBind) {
  104768. effect.onBind(effect);
  104769. }
  104770. if (effect._onBindObservable) {
  104771. effect._onBindObservable.notifyObservers(effect);
  104772. }
  104773. };
  104774. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  104775. if (zOffset === void 0) { zOffset = 0; }
  104776. if (reverseSide === void 0) { reverseSide = false; }
  104777. };
  104778. NullEngine.prototype.setIntArray = function (uniform, array) {
  104779. };
  104780. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  104781. };
  104782. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  104783. };
  104784. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  104785. };
  104786. NullEngine.prototype.setFloatArray = function (uniform, array) {
  104787. };
  104788. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  104789. };
  104790. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  104791. };
  104792. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  104793. };
  104794. NullEngine.prototype.setArray = function (uniform, array) {
  104795. };
  104796. NullEngine.prototype.setArray2 = function (uniform, array) {
  104797. };
  104798. NullEngine.prototype.setArray3 = function (uniform, array) {
  104799. };
  104800. NullEngine.prototype.setArray4 = function (uniform, array) {
  104801. };
  104802. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  104803. };
  104804. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  104805. };
  104806. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  104807. };
  104808. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  104809. };
  104810. NullEngine.prototype.setFloat = function (uniform, value) {
  104811. };
  104812. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  104813. };
  104814. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  104815. };
  104816. NullEngine.prototype.setBool = function (uniform, bool) {
  104817. };
  104818. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  104819. };
  104820. NullEngine.prototype.setColor3 = function (uniform, color3) {
  104821. };
  104822. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  104823. };
  104824. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  104825. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  104826. if (this._alphaMode === mode) {
  104827. return;
  104828. }
  104829. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  104830. if (!noDepthWriteChange) {
  104831. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  104832. }
  104833. this._alphaMode = mode;
  104834. };
  104835. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  104836. };
  104837. NullEngine.prototype.wipeCaches = function (bruteForce) {
  104838. if (this.preventCacheWipeBetweenFrames) {
  104839. return;
  104840. }
  104841. this.resetTextureCache();
  104842. this._currentEffect = null;
  104843. if (bruteForce) {
  104844. this._currentProgram = null;
  104845. this._stencilState.reset();
  104846. this._depthCullingState.reset();
  104847. this._alphaState.reset();
  104848. }
  104849. this._cachedVertexBuffers = null;
  104850. this._cachedIndexBuffer = null;
  104851. this._cachedEffectForVertexBuffers = null;
  104852. };
  104853. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  104854. };
  104855. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  104856. };
  104857. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  104858. };
  104859. /** @hidden */
  104860. NullEngine.prototype._createTexture = function () {
  104861. return {};
  104862. };
  104863. /** @hidden */
  104864. NullEngine.prototype._releaseTexture = function (texture) {
  104865. };
  104866. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  104867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104868. if (onLoad === void 0) { onLoad = null; }
  104869. if (onError === void 0) { onError = null; }
  104870. if (buffer === void 0) { buffer = null; }
  104871. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  104872. var url = String(urlArg);
  104873. texture.url = url;
  104874. texture.generateMipMaps = !noMipmap;
  104875. texture.samplingMode = samplingMode;
  104876. texture.invertY = invertY;
  104877. texture.baseWidth = this._options.textureSize;
  104878. texture.baseHeight = this._options.textureSize;
  104879. texture.width = this._options.textureSize;
  104880. texture.height = this._options.textureSize;
  104881. if (format) {
  104882. texture.format = format;
  104883. }
  104884. texture.isReady = true;
  104885. if (onLoad) {
  104886. onLoad();
  104887. }
  104888. this._internalTexturesCache.push(texture);
  104889. return texture;
  104890. };
  104891. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  104892. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  104893. if (options !== undefined && typeof options === "object") {
  104894. fullOptions.generateMipMaps = options.generateMipMaps;
  104895. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  104896. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  104897. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  104898. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  104899. }
  104900. else {
  104901. fullOptions.generateMipMaps = options;
  104902. fullOptions.generateDepthBuffer = true;
  104903. fullOptions.generateStencilBuffer = false;
  104904. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104905. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104906. }
  104907. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  104908. var width = size.width || size;
  104909. var height = size.height || size;
  104910. texture._depthStencilBuffer = {};
  104911. texture._framebuffer = {};
  104912. texture.baseWidth = width;
  104913. texture.baseHeight = height;
  104914. texture.width = width;
  104915. texture.height = height;
  104916. texture.isReady = true;
  104917. texture.samples = 1;
  104918. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  104919. texture.samplingMode = fullOptions.samplingMode;
  104920. texture.type = fullOptions.type;
  104921. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  104922. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  104923. this._internalTexturesCache.push(texture);
  104924. return texture;
  104925. };
  104926. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  104927. texture.samplingMode = samplingMode;
  104928. };
  104929. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  104930. if (this._currentRenderTarget) {
  104931. this.unBindFramebuffer(this._currentRenderTarget);
  104932. }
  104933. this._currentRenderTarget = texture;
  104934. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  104935. if (this._cachedViewport && !forceFullscreenViewport) {
  104936. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  104937. }
  104938. };
  104939. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  104940. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  104941. this._currentRenderTarget = null;
  104942. if (onBeforeUnbind) {
  104943. if (texture._MSAAFramebuffer) {
  104944. this._currentFramebuffer = texture._framebuffer;
  104945. }
  104946. onBeforeUnbind();
  104947. }
  104948. this._currentFramebuffer = null;
  104949. };
  104950. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  104951. var vbo = {
  104952. capacity: 1,
  104953. references: 1,
  104954. is32Bits: false
  104955. };
  104956. return vbo;
  104957. };
  104958. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  104959. if (premulAlpha === void 0) { premulAlpha = false; }
  104960. };
  104961. /**
  104962. * @hidden
  104963. * Get the current error code of the webGL context
  104964. * @returns the error code
  104965. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  104966. */
  104967. NullEngine.prototype.getError = function () {
  104968. return 0;
  104969. };
  104970. /** @hidden */
  104971. NullEngine.prototype._getUnpackAlignement = function () {
  104972. return 1;
  104973. };
  104974. /** @hidden */
  104975. NullEngine.prototype._unpackFlipY = function (value) {
  104976. };
  104977. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  104978. if (offset === void 0) { offset = 0; }
  104979. };
  104980. /**
  104981. * Updates a dynamic vertex buffer.
  104982. * @param vertexBuffer the vertex buffer to update
  104983. * @param data the data used to update the vertex buffer
  104984. * @param byteOffset the byte offset of the data (optional)
  104985. * @param byteLength the byte length of the data (optional)
  104986. */
  104987. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  104988. };
  104989. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  104990. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  104991. this._boundTexturesCache[this._activeChannel] = texture;
  104992. return true;
  104993. }
  104994. return false;
  104995. };
  104996. /** @hidden */
  104997. NullEngine.prototype._bindTexture = function (channel, texture) {
  104998. if (channel < 0) {
  104999. return;
  105000. }
  105001. this._bindTextureDirectly(0, texture);
  105002. };
  105003. /** @hidden */
  105004. NullEngine.prototype._releaseBuffer = function (buffer) {
  105005. buffer.references--;
  105006. if (buffer.references === 0) {
  105007. return true;
  105008. }
  105009. return false;
  105010. };
  105011. NullEngine.prototype.releaseEffects = function () {
  105012. };
  105013. NullEngine.prototype.displayLoadingUI = function () {
  105014. };
  105015. NullEngine.prototype.hideLoadingUI = function () {
  105016. };
  105017. /** @hidden */
  105018. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  105019. if (faceIndex === void 0) { faceIndex = 0; }
  105020. if (lod === void 0) { lod = 0; }
  105021. };
  105022. /** @hidden */
  105023. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  105024. if (faceIndex === void 0) { faceIndex = 0; }
  105025. if (lod === void 0) { lod = 0; }
  105026. };
  105027. /** @hidden */
  105028. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  105029. if (faceIndex === void 0) { faceIndex = 0; }
  105030. if (lod === void 0) { lod = 0; }
  105031. };
  105032. /** @hidden */
  105033. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  105034. if (faceIndex === void 0) { faceIndex = 0; }
  105035. if (lod === void 0) { lod = 0; }
  105036. };
  105037. return NullEngine;
  105038. }(BABYLON.Engine));
  105039. BABYLON.NullEngine = NullEngine;
  105040. })(BABYLON || (BABYLON = {}));
  105041. //# sourceMappingURL=babylon.nullEngine.js.map
  105042. var BABYLON;
  105043. (function (BABYLON) {
  105044. /**
  105045. * This class can be used to get instrumentation data from a Babylon engine
  105046. */
  105047. var EngineInstrumentation = /** @class */ (function () {
  105048. function EngineInstrumentation(engine) {
  105049. this.engine = engine;
  105050. this._captureGPUFrameTime = false;
  105051. this._gpuFrameTime = new BABYLON.PerfCounter();
  105052. this._captureShaderCompilationTime = false;
  105053. this._shaderCompilationTime = new BABYLON.PerfCounter();
  105054. // Observers
  105055. this._onBeginFrameObserver = null;
  105056. this._onEndFrameObserver = null;
  105057. this._onBeforeShaderCompilationObserver = null;
  105058. this._onAfterShaderCompilationObserver = null;
  105059. }
  105060. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  105061. // Properties
  105062. /**
  105063. * Gets the perf counter used for GPU frame time
  105064. */
  105065. get: function () {
  105066. return this._gpuFrameTime;
  105067. },
  105068. enumerable: true,
  105069. configurable: true
  105070. });
  105071. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  105072. /**
  105073. * Gets the GPU frame time capture status
  105074. */
  105075. get: function () {
  105076. return this._captureGPUFrameTime;
  105077. },
  105078. /**
  105079. * Enable or disable the GPU frame time capture
  105080. */
  105081. set: function (value) {
  105082. var _this = this;
  105083. if (value === this._captureGPUFrameTime) {
  105084. return;
  105085. }
  105086. this._captureGPUFrameTime = value;
  105087. if (value) {
  105088. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  105089. if (!_this._gpuFrameTimeToken) {
  105090. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  105091. }
  105092. });
  105093. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  105094. if (!_this._gpuFrameTimeToken) {
  105095. return;
  105096. }
  105097. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  105098. if (time > -1) {
  105099. _this._gpuFrameTimeToken = null;
  105100. _this._gpuFrameTime.fetchNewFrame();
  105101. _this._gpuFrameTime.addCount(time, true);
  105102. }
  105103. });
  105104. }
  105105. else {
  105106. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  105107. this._onBeginFrameObserver = null;
  105108. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  105109. this._onEndFrameObserver = null;
  105110. }
  105111. },
  105112. enumerable: true,
  105113. configurable: true
  105114. });
  105115. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  105116. /**
  105117. * Gets the perf counter used for shader compilation time
  105118. */
  105119. get: function () {
  105120. return this._shaderCompilationTime;
  105121. },
  105122. enumerable: true,
  105123. configurable: true
  105124. });
  105125. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  105126. /**
  105127. * Gets the shader compilation time capture status
  105128. */
  105129. get: function () {
  105130. return this._captureShaderCompilationTime;
  105131. },
  105132. /**
  105133. * Enable or disable the shader compilation time capture
  105134. */
  105135. set: function (value) {
  105136. var _this = this;
  105137. if (value === this._captureShaderCompilationTime) {
  105138. return;
  105139. }
  105140. this._captureShaderCompilationTime = value;
  105141. if (value) {
  105142. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  105143. _this._shaderCompilationTime.fetchNewFrame();
  105144. _this._shaderCompilationTime.beginMonitoring();
  105145. });
  105146. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  105147. _this._shaderCompilationTime.endMonitoring();
  105148. });
  105149. }
  105150. else {
  105151. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  105152. this._onBeforeShaderCompilationObserver = null;
  105153. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  105154. this._onAfterShaderCompilationObserver = null;
  105155. }
  105156. },
  105157. enumerable: true,
  105158. configurable: true
  105159. });
  105160. EngineInstrumentation.prototype.dispose = function () {
  105161. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  105162. this._onBeginFrameObserver = null;
  105163. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  105164. this._onEndFrameObserver = null;
  105165. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  105166. this._onBeforeShaderCompilationObserver = null;
  105167. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  105168. this._onAfterShaderCompilationObserver = null;
  105169. this.engine = null;
  105170. };
  105171. return EngineInstrumentation;
  105172. }());
  105173. BABYLON.EngineInstrumentation = EngineInstrumentation;
  105174. })(BABYLON || (BABYLON = {}));
  105175. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  105176. var BABYLON;
  105177. (function (BABYLON) {
  105178. /**
  105179. * This class can be used to get instrumentation data from a Babylon engine
  105180. */
  105181. var SceneInstrumentation = /** @class */ (function () {
  105182. function SceneInstrumentation(scene) {
  105183. var _this = this;
  105184. this.scene = scene;
  105185. this._captureActiveMeshesEvaluationTime = false;
  105186. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  105187. this._captureRenderTargetsRenderTime = false;
  105188. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  105189. this._captureFrameTime = false;
  105190. this._frameTime = new BABYLON.PerfCounter();
  105191. this._captureRenderTime = false;
  105192. this._renderTime = new BABYLON.PerfCounter();
  105193. this._captureInterFrameTime = false;
  105194. this._interFrameTime = new BABYLON.PerfCounter();
  105195. this._captureParticlesRenderTime = false;
  105196. this._particlesRenderTime = new BABYLON.PerfCounter();
  105197. this._captureSpritesRenderTime = false;
  105198. this._spritesRenderTime = new BABYLON.PerfCounter();
  105199. this._capturePhysicsTime = false;
  105200. this._physicsTime = new BABYLON.PerfCounter();
  105201. this._captureAnimationsTime = false;
  105202. this._animationsTime = new BABYLON.PerfCounter();
  105203. this._captureCameraRenderTime = false;
  105204. this._cameraRenderTime = new BABYLON.PerfCounter();
  105205. // Observers
  105206. this._onBeforeActiveMeshesEvaluationObserver = null;
  105207. this._onAfterActiveMeshesEvaluationObserver = null;
  105208. this._onBeforeRenderTargetsRenderObserver = null;
  105209. this._onAfterRenderTargetsRenderObserver = null;
  105210. this._onAfterRenderObserver = null;
  105211. this._onBeforeDrawPhaseObserver = null;
  105212. this._onAfterDrawPhaseObserver = null;
  105213. this._onBeforeAnimationsObserver = null;
  105214. this._onBeforeParticlesRenderingObserver = null;
  105215. this._onAfterParticlesRenderingObserver = null;
  105216. this._onBeforeSpritesRenderingObserver = null;
  105217. this._onAfterSpritesRenderingObserver = null;
  105218. this._onBeforePhysicsObserver = null;
  105219. this._onAfterPhysicsObserver = null;
  105220. this._onAfterAnimationsObserver = null;
  105221. this._onBeforeCameraRenderObserver = null;
  105222. this._onAfterCameraRenderObserver = null;
  105223. // Before render
  105224. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  105225. if (_this._captureActiveMeshesEvaluationTime) {
  105226. _this._activeMeshesEvaluationTime.fetchNewFrame();
  105227. }
  105228. if (_this._captureRenderTargetsRenderTime) {
  105229. _this._renderTargetsRenderTime.fetchNewFrame();
  105230. }
  105231. if (_this._captureFrameTime) {
  105232. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  105233. _this._frameTime.beginMonitoring();
  105234. }
  105235. if (_this._captureInterFrameTime) {
  105236. _this._interFrameTime.endMonitoring();
  105237. }
  105238. if (_this._captureParticlesRenderTime) {
  105239. _this._particlesRenderTime.fetchNewFrame();
  105240. }
  105241. if (_this._captureSpritesRenderTime) {
  105242. _this._spritesRenderTime.fetchNewFrame();
  105243. }
  105244. if (_this._captureAnimationsTime) {
  105245. _this._animationsTime.beginMonitoring();
  105246. }
  105247. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  105248. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  105249. });
  105250. // After render
  105251. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  105252. if (_this._captureFrameTime) {
  105253. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  105254. _this._frameTime.endMonitoring();
  105255. }
  105256. if (_this._captureRenderTime) {
  105257. _this._renderTime.endMonitoring(false);
  105258. }
  105259. if (_this._captureInterFrameTime) {
  105260. _this._interFrameTime.beginMonitoring();
  105261. }
  105262. });
  105263. }
  105264. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  105265. // Properties
  105266. /**
  105267. * Gets the perf counter used for active meshes evaluation time
  105268. */
  105269. get: function () {
  105270. return this._activeMeshesEvaluationTime;
  105271. },
  105272. enumerable: true,
  105273. configurable: true
  105274. });
  105275. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  105276. /**
  105277. * Gets the active meshes evaluation time capture status
  105278. */
  105279. get: function () {
  105280. return this._captureActiveMeshesEvaluationTime;
  105281. },
  105282. /**
  105283. * Enable or disable the active meshes evaluation time capture
  105284. */
  105285. set: function (value) {
  105286. var _this = this;
  105287. if (value === this._captureActiveMeshesEvaluationTime) {
  105288. return;
  105289. }
  105290. this._captureActiveMeshesEvaluationTime = value;
  105291. if (value) {
  105292. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  105293. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  105294. _this._activeMeshesEvaluationTime.beginMonitoring();
  105295. });
  105296. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  105297. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  105298. _this._activeMeshesEvaluationTime.endMonitoring();
  105299. });
  105300. }
  105301. else {
  105302. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  105303. this._onBeforeActiveMeshesEvaluationObserver = null;
  105304. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  105305. this._onAfterActiveMeshesEvaluationObserver = null;
  105306. }
  105307. },
  105308. enumerable: true,
  105309. configurable: true
  105310. });
  105311. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  105312. /**
  105313. * Gets the perf counter used for render targets render time
  105314. */
  105315. get: function () {
  105316. return this._renderTargetsRenderTime;
  105317. },
  105318. enumerable: true,
  105319. configurable: true
  105320. });
  105321. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  105322. /**
  105323. * Gets the render targets render time capture status
  105324. */
  105325. get: function () {
  105326. return this._captureRenderTargetsRenderTime;
  105327. },
  105328. /**
  105329. * Enable or disable the render targets render time capture
  105330. */
  105331. set: function (value) {
  105332. var _this = this;
  105333. if (value === this._captureRenderTargetsRenderTime) {
  105334. return;
  105335. }
  105336. this._captureRenderTargetsRenderTime = value;
  105337. if (value) {
  105338. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  105339. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  105340. _this._renderTargetsRenderTime.beginMonitoring();
  105341. });
  105342. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  105343. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  105344. _this._renderTargetsRenderTime.endMonitoring(false);
  105345. });
  105346. }
  105347. else {
  105348. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  105349. this._onBeforeRenderTargetsRenderObserver = null;
  105350. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  105351. this._onAfterRenderTargetsRenderObserver = null;
  105352. }
  105353. },
  105354. enumerable: true,
  105355. configurable: true
  105356. });
  105357. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  105358. /**
  105359. * Gets the perf counter used for particles render time
  105360. */
  105361. get: function () {
  105362. return this._particlesRenderTime;
  105363. },
  105364. enumerable: true,
  105365. configurable: true
  105366. });
  105367. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  105368. /**
  105369. * Gets the particles render time capture status
  105370. */
  105371. get: function () {
  105372. return this._captureParticlesRenderTime;
  105373. },
  105374. /**
  105375. * Enable or disable the particles render time capture
  105376. */
  105377. set: function (value) {
  105378. var _this = this;
  105379. if (value === this._captureParticlesRenderTime) {
  105380. return;
  105381. }
  105382. this._captureParticlesRenderTime = value;
  105383. if (value) {
  105384. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  105385. BABYLON.Tools.StartPerformanceCounter("Particles");
  105386. _this._particlesRenderTime.beginMonitoring();
  105387. });
  105388. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  105389. BABYLON.Tools.EndPerformanceCounter("Particles");
  105390. _this._particlesRenderTime.endMonitoring(false);
  105391. });
  105392. }
  105393. else {
  105394. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  105395. this._onBeforeParticlesRenderingObserver = null;
  105396. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  105397. this._onAfterParticlesRenderingObserver = null;
  105398. }
  105399. },
  105400. enumerable: true,
  105401. configurable: true
  105402. });
  105403. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  105404. /**
  105405. * Gets the perf counter used for sprites render time
  105406. */
  105407. get: function () {
  105408. return this._spritesRenderTime;
  105409. },
  105410. enumerable: true,
  105411. configurable: true
  105412. });
  105413. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  105414. /**
  105415. * Gets the sprites render time capture status
  105416. */
  105417. get: function () {
  105418. return this._captureSpritesRenderTime;
  105419. },
  105420. /**
  105421. * Enable or disable the sprites render time capture
  105422. */
  105423. set: function (value) {
  105424. var _this = this;
  105425. if (value === this._captureSpritesRenderTime) {
  105426. return;
  105427. }
  105428. this._captureSpritesRenderTime = value;
  105429. if (!this.scene.spriteManagers) {
  105430. return;
  105431. }
  105432. if (value) {
  105433. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  105434. BABYLON.Tools.StartPerformanceCounter("Sprites");
  105435. _this._spritesRenderTime.beginMonitoring();
  105436. });
  105437. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  105438. BABYLON.Tools.EndPerformanceCounter("Sprites");
  105439. _this._spritesRenderTime.endMonitoring(false);
  105440. });
  105441. }
  105442. else {
  105443. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  105444. this._onBeforeSpritesRenderingObserver = null;
  105445. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  105446. this._onAfterSpritesRenderingObserver = null;
  105447. }
  105448. },
  105449. enumerable: true,
  105450. configurable: true
  105451. });
  105452. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  105453. /**
  105454. * Gets the perf counter used for physics time
  105455. */
  105456. get: function () {
  105457. return this._physicsTime;
  105458. },
  105459. enumerable: true,
  105460. configurable: true
  105461. });
  105462. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  105463. /**
  105464. * Gets the physics time capture status
  105465. */
  105466. get: function () {
  105467. return this._capturePhysicsTime;
  105468. },
  105469. /**
  105470. * Enable or disable the physics time capture
  105471. */
  105472. set: function (value) {
  105473. var _this = this;
  105474. if (value === this._capturePhysicsTime) {
  105475. return;
  105476. }
  105477. this._capturePhysicsTime = value;
  105478. if (value) {
  105479. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  105480. BABYLON.Tools.StartPerformanceCounter("Physics");
  105481. _this._physicsTime.beginMonitoring();
  105482. });
  105483. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  105484. BABYLON.Tools.EndPerformanceCounter("Physics");
  105485. _this._physicsTime.endMonitoring();
  105486. });
  105487. }
  105488. else {
  105489. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  105490. this._onBeforePhysicsObserver = null;
  105491. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  105492. this._onAfterPhysicsObserver = null;
  105493. }
  105494. },
  105495. enumerable: true,
  105496. configurable: true
  105497. });
  105498. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  105499. /**
  105500. * Gets the perf counter used for animations time
  105501. */
  105502. get: function () {
  105503. return this._animationsTime;
  105504. },
  105505. enumerable: true,
  105506. configurable: true
  105507. });
  105508. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  105509. /**
  105510. * Gets the animations time capture status
  105511. */
  105512. get: function () {
  105513. return this._captureAnimationsTime;
  105514. },
  105515. /**
  105516. * Enable or disable the animations time capture
  105517. */
  105518. set: function (value) {
  105519. var _this = this;
  105520. if (value === this._captureAnimationsTime) {
  105521. return;
  105522. }
  105523. this._captureAnimationsTime = value;
  105524. if (value) {
  105525. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  105526. _this._animationsTime.endMonitoring();
  105527. });
  105528. }
  105529. else {
  105530. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  105531. this._onAfterAnimationsObserver = null;
  105532. }
  105533. },
  105534. enumerable: true,
  105535. configurable: true
  105536. });
  105537. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  105538. /**
  105539. * Gets the perf counter used for frame time capture
  105540. */
  105541. get: function () {
  105542. return this._frameTime;
  105543. },
  105544. enumerable: true,
  105545. configurable: true
  105546. });
  105547. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  105548. /**
  105549. * Gets the frame time capture status
  105550. */
  105551. get: function () {
  105552. return this._captureFrameTime;
  105553. },
  105554. /**
  105555. * Enable or disable the frame time capture
  105556. */
  105557. set: function (value) {
  105558. this._captureFrameTime = value;
  105559. },
  105560. enumerable: true,
  105561. configurable: true
  105562. });
  105563. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  105564. /**
  105565. * Gets the perf counter used for inter-frames time capture
  105566. */
  105567. get: function () {
  105568. return this._interFrameTime;
  105569. },
  105570. enumerable: true,
  105571. configurable: true
  105572. });
  105573. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  105574. /**
  105575. * Gets the inter-frames time capture status
  105576. */
  105577. get: function () {
  105578. return this._captureInterFrameTime;
  105579. },
  105580. /**
  105581. * Enable or disable the inter-frames time capture
  105582. */
  105583. set: function (value) {
  105584. this._captureInterFrameTime = value;
  105585. },
  105586. enumerable: true,
  105587. configurable: true
  105588. });
  105589. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  105590. /**
  105591. * Gets the perf counter used for render time capture
  105592. */
  105593. get: function () {
  105594. return this._renderTime;
  105595. },
  105596. enumerable: true,
  105597. configurable: true
  105598. });
  105599. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  105600. /**
  105601. * Gets the render time capture status
  105602. */
  105603. get: function () {
  105604. return this._captureRenderTime;
  105605. },
  105606. /**
  105607. * Enable or disable the render time capture
  105608. */
  105609. set: function (value) {
  105610. var _this = this;
  105611. if (value === this._captureRenderTime) {
  105612. return;
  105613. }
  105614. this._captureRenderTime = value;
  105615. if (value) {
  105616. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  105617. _this._renderTime.beginMonitoring();
  105618. BABYLON.Tools.StartPerformanceCounter("Main render");
  105619. });
  105620. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  105621. _this._renderTime.endMonitoring(false);
  105622. BABYLON.Tools.EndPerformanceCounter("Main render");
  105623. });
  105624. }
  105625. else {
  105626. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105627. this._onBeforeDrawPhaseObserver = null;
  105628. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105629. this._onAfterDrawPhaseObserver = null;
  105630. }
  105631. },
  105632. enumerable: true,
  105633. configurable: true
  105634. });
  105635. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  105636. /**
  105637. * Gets the perf counter used for camera render time capture
  105638. */
  105639. get: function () {
  105640. return this._cameraRenderTime;
  105641. },
  105642. enumerable: true,
  105643. configurable: true
  105644. });
  105645. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  105646. /**
  105647. * Gets the camera render time capture status
  105648. */
  105649. get: function () {
  105650. return this._captureCameraRenderTime;
  105651. },
  105652. /**
  105653. * Enable or disable the camera render time capture
  105654. */
  105655. set: function (value) {
  105656. var _this = this;
  105657. if (value === this._captureCameraRenderTime) {
  105658. return;
  105659. }
  105660. this._captureCameraRenderTime = value;
  105661. if (value) {
  105662. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  105663. _this._cameraRenderTime.beginMonitoring();
  105664. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  105665. });
  105666. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  105667. _this._cameraRenderTime.endMonitoring(false);
  105668. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  105669. });
  105670. }
  105671. else {
  105672. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105673. this._onBeforeCameraRenderObserver = null;
  105674. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105675. this._onAfterCameraRenderObserver = null;
  105676. }
  105677. },
  105678. enumerable: true,
  105679. configurable: true
  105680. });
  105681. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  105682. /**
  105683. * Gets the perf counter used for draw calls
  105684. */
  105685. get: function () {
  105686. return this.scene.getEngine()._drawCalls;
  105687. },
  105688. enumerable: true,
  105689. configurable: true
  105690. });
  105691. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  105692. /**
  105693. * Gets the perf counter used for texture collisions
  105694. */
  105695. get: function () {
  105696. return this.scene.getEngine()._textureCollisions;
  105697. },
  105698. enumerable: true,
  105699. configurable: true
  105700. });
  105701. SceneInstrumentation.prototype.dispose = function () {
  105702. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105703. this._onAfterRenderObserver = null;
  105704. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  105705. this._onBeforeActiveMeshesEvaluationObserver = null;
  105706. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  105707. this._onAfterActiveMeshesEvaluationObserver = null;
  105708. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  105709. this._onBeforeRenderTargetsRenderObserver = null;
  105710. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  105711. this._onAfterRenderTargetsRenderObserver = null;
  105712. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  105713. this._onBeforeAnimationsObserver = null;
  105714. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  105715. this._onBeforeParticlesRenderingObserver = null;
  105716. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  105717. this._onAfterParticlesRenderingObserver = null;
  105718. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  105719. this._onBeforeSpritesRenderingObserver = null;
  105720. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  105721. this._onAfterSpritesRenderingObserver = null;
  105722. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105723. this._onBeforeDrawPhaseObserver = null;
  105724. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105725. this._onAfterDrawPhaseObserver = null;
  105726. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  105727. this._onBeforePhysicsObserver = null;
  105728. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  105729. this._onAfterPhysicsObserver = null;
  105730. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  105731. this._onAfterAnimationsObserver = null;
  105732. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105733. this._onBeforeCameraRenderObserver = null;
  105734. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105735. this._onAfterCameraRenderObserver = null;
  105736. this.scene = null;
  105737. };
  105738. return SceneInstrumentation;
  105739. }());
  105740. BABYLON.SceneInstrumentation = SceneInstrumentation;
  105741. })(BABYLON || (BABYLON = {}));
  105742. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  105743. var BABYLON;
  105744. (function (BABYLON) {
  105745. /**
  105746. * @hidden
  105747. **/
  105748. var _TimeToken = /** @class */ (function () {
  105749. function _TimeToken() {
  105750. this._timeElapsedQueryEnded = false;
  105751. }
  105752. return _TimeToken;
  105753. }());
  105754. BABYLON._TimeToken = _TimeToken;
  105755. })(BABYLON || (BABYLON = {}));
  105756. //# sourceMappingURL=babylon.timeToken.js.map
  105757. var BABYLON;
  105758. (function (BABYLON) {
  105759. /**
  105760. * Background material defines definition.
  105761. * @hidden Mainly internal Use
  105762. */
  105763. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  105764. __extends(BackgroundMaterialDefines, _super);
  105765. /**
  105766. * Constructor of the defines.
  105767. */
  105768. function BackgroundMaterialDefines() {
  105769. var _this = _super.call(this) || this;
  105770. /**
  105771. * True if the diffuse texture is in use.
  105772. */
  105773. _this.DIFFUSE = false;
  105774. /**
  105775. * The direct UV channel to use.
  105776. */
  105777. _this.DIFFUSEDIRECTUV = 0;
  105778. /**
  105779. * True if the diffuse texture is in gamma space.
  105780. */
  105781. _this.GAMMADIFFUSE = false;
  105782. /**
  105783. * True if the diffuse texture has opacity in the alpha channel.
  105784. */
  105785. _this.DIFFUSEHASALPHA = false;
  105786. /**
  105787. * True if you want the material to fade to transparent at grazing angle.
  105788. */
  105789. _this.OPACITYFRESNEL = false;
  105790. /**
  105791. * True if an extra blur needs to be added in the reflection.
  105792. */
  105793. _this.REFLECTIONBLUR = false;
  105794. /**
  105795. * True if you want the material to fade to reflection at grazing angle.
  105796. */
  105797. _this.REFLECTIONFRESNEL = false;
  105798. /**
  105799. * True if you want the material to falloff as far as you move away from the scene center.
  105800. */
  105801. _this.REFLECTIONFALLOFF = false;
  105802. /**
  105803. * False if the current Webgl implementation does not support the texture lod extension.
  105804. */
  105805. _this.TEXTURELODSUPPORT = false;
  105806. /**
  105807. * True to ensure the data are premultiplied.
  105808. */
  105809. _this.PREMULTIPLYALPHA = false;
  105810. /**
  105811. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  105812. */
  105813. _this.USERGBCOLOR = false;
  105814. /**
  105815. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  105816. * stays aligned with the desired configuration.
  105817. */
  105818. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  105819. /**
  105820. * True to add noise in order to reduce the banding effect.
  105821. */
  105822. _this.NOISE = false;
  105823. /**
  105824. * is the reflection texture in BGR color scheme?
  105825. * Mainly used to solve a bug in ios10 video tag
  105826. */
  105827. _this.REFLECTIONBGR = false;
  105828. _this.IMAGEPROCESSING = false;
  105829. _this.VIGNETTE = false;
  105830. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  105831. _this.VIGNETTEBLENDMODEOPAQUE = false;
  105832. _this.TONEMAPPING = false;
  105833. _this.TONEMAPPING_ACES = false;
  105834. _this.CONTRAST = false;
  105835. _this.COLORCURVES = false;
  105836. _this.COLORGRADING = false;
  105837. _this.COLORGRADING3D = false;
  105838. _this.SAMPLER3DGREENDEPTH = false;
  105839. _this.SAMPLER3DBGRMAP = false;
  105840. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  105841. _this.EXPOSURE = false;
  105842. // Reflection.
  105843. _this.REFLECTION = false;
  105844. _this.REFLECTIONMAP_3D = false;
  105845. _this.REFLECTIONMAP_SPHERICAL = false;
  105846. _this.REFLECTIONMAP_PLANAR = false;
  105847. _this.REFLECTIONMAP_CUBIC = false;
  105848. _this.REFLECTIONMAP_PROJECTION = false;
  105849. _this.REFLECTIONMAP_SKYBOX = false;
  105850. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105851. _this.REFLECTIONMAP_EXPLICIT = false;
  105852. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105853. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105854. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105855. _this.INVERTCUBICMAP = false;
  105856. _this.REFLECTIONMAP_OPPOSITEZ = false;
  105857. _this.LODINREFLECTIONALPHA = false;
  105858. _this.GAMMAREFLECTION = false;
  105859. _this.RGBDREFLECTION = false;
  105860. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  105861. // Default BJS.
  105862. _this.MAINUV1 = false;
  105863. _this.MAINUV2 = false;
  105864. _this.UV1 = false;
  105865. _this.UV2 = false;
  105866. _this.CLIPPLANE = false;
  105867. _this.CLIPPLANE2 = false;
  105868. _this.CLIPPLANE3 = false;
  105869. _this.CLIPPLANE4 = false;
  105870. _this.POINTSIZE = false;
  105871. _this.FOG = false;
  105872. _this.NORMAL = false;
  105873. _this.NUM_BONE_INFLUENCERS = 0;
  105874. _this.BonesPerMesh = 0;
  105875. _this.INSTANCES = false;
  105876. _this.SHADOWFLOAT = false;
  105877. _this.rebuild();
  105878. return _this;
  105879. }
  105880. return BackgroundMaterialDefines;
  105881. }(BABYLON.MaterialDefines));
  105882. /**
  105883. * Background material used to create an efficient environement around your scene.
  105884. */
  105885. var BackgroundMaterial = /** @class */ (function (_super) {
  105886. __extends(BackgroundMaterial, _super);
  105887. /**
  105888. * Instantiates a Background Material in the given scene
  105889. * @param name The friendly name of the material
  105890. * @param scene The scene to add the material to
  105891. */
  105892. function BackgroundMaterial(name, scene) {
  105893. var _this = _super.call(this, name, scene) || this;
  105894. /**
  105895. * Key light Color (multiply against the environement texture)
  105896. */
  105897. _this.primaryColor = BABYLON.Color3.White();
  105898. _this._primaryColorShadowLevel = 0;
  105899. _this._primaryColorHighlightLevel = 0;
  105900. /**
  105901. * Reflection Texture used in the material.
  105902. * Should be author in a specific way for the best result (refer to the documentation).
  105903. */
  105904. _this.reflectionTexture = null;
  105905. /**
  105906. * Reflection Texture level of blur.
  105907. *
  105908. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  105909. * texture twice.
  105910. */
  105911. _this.reflectionBlur = 0;
  105912. /**
  105913. * Diffuse Texture used in the material.
  105914. * Should be author in a specific way for the best result (refer to the documentation).
  105915. */
  105916. _this.diffuseTexture = null;
  105917. _this._shadowLights = null;
  105918. /**
  105919. * Specify the list of lights casting shadow on the material.
  105920. * All scene shadow lights will be included if null.
  105921. */
  105922. _this.shadowLights = null;
  105923. /**
  105924. * Helps adjusting the shadow to a softer level if required.
  105925. * 0 means black shadows and 1 means no shadows.
  105926. */
  105927. _this.shadowLevel = 0;
  105928. /**
  105929. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  105930. * It is usually zero but might be interesting to modify according to your setup.
  105931. */
  105932. _this.sceneCenter = BABYLON.Vector3.Zero();
  105933. /**
  105934. * This helps specifying that the material is falling off to the sky box at grazing angle.
  105935. * This helps ensuring a nice transition when the camera goes under the ground.
  105936. */
  105937. _this.opacityFresnel = true;
  105938. /**
  105939. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  105940. * This helps adding a mirror texture on the ground.
  105941. */
  105942. _this.reflectionFresnel = false;
  105943. /**
  105944. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  105945. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  105946. */
  105947. _this.reflectionFalloffDistance = 0.0;
  105948. /**
  105949. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  105950. */
  105951. _this.reflectionAmount = 1.0;
  105952. /**
  105953. * This specifies the weight of the reflection at grazing angle.
  105954. */
  105955. _this.reflectionReflectance0 = 0.05;
  105956. /**
  105957. * This specifies the weight of the reflection at a perpendicular point of view.
  105958. */
  105959. _this.reflectionReflectance90 = 0.5;
  105960. /**
  105961. * Helps to directly use the maps channels instead of their level.
  105962. */
  105963. _this.useRGBColor = true;
  105964. /**
  105965. * This helps reducing the banding effect that could occur on the background.
  105966. */
  105967. _this.enableNoise = false;
  105968. _this._fovMultiplier = 1.0;
  105969. /**
  105970. * Enable the FOV adjustment feature controlled by fovMultiplier.
  105971. */
  105972. _this.useEquirectangularFOV = false;
  105973. _this._maxSimultaneousLights = 4;
  105974. /**
  105975. * Number of Simultaneous lights allowed on the material.
  105976. */
  105977. _this.maxSimultaneousLights = 4;
  105978. /**
  105979. * Keep track of the image processing observer to allow dispose and replace.
  105980. */
  105981. _this._imageProcessingObserver = null;
  105982. /**
  105983. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  105984. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  105985. */
  105986. _this.switchToBGR = false;
  105987. // Temp values kept as cache in the material.
  105988. _this._renderTargets = new BABYLON.SmartArray(16);
  105989. _this._reflectionControls = BABYLON.Vector4.Zero();
  105990. _this._white = BABYLON.Color3.White();
  105991. _this._primaryShadowColor = BABYLON.Color3.Black();
  105992. _this._primaryHighlightColor = BABYLON.Color3.Black();
  105993. // Setup the default processing configuration to the scene.
  105994. _this._attachImageProcessingConfiguration(null);
  105995. _this.getRenderTargetTextures = function () {
  105996. _this._renderTargets.reset();
  105997. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  105998. _this._renderTargets.push(_this._diffuseTexture);
  105999. }
  106000. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  106001. _this._renderTargets.push(_this._reflectionTexture);
  106002. }
  106003. return _this._renderTargets;
  106004. };
  106005. return _this;
  106006. }
  106007. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  106008. /**
  106009. * Experimental Internal Use Only.
  106010. *
  106011. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  106012. * This acts as a helper to set the primary color to a more "human friendly" value.
  106013. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  106014. * output color as close as possible from the chosen value.
  106015. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  106016. * part of lighting setup.)
  106017. */
  106018. get: function () {
  106019. return this.__perceptualColor;
  106020. },
  106021. set: function (value) {
  106022. this.__perceptualColor = value;
  106023. this._computePrimaryColorFromPerceptualColor();
  106024. this._markAllSubMeshesAsLightsDirty();
  106025. },
  106026. enumerable: true,
  106027. configurable: true
  106028. });
  106029. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  106030. /**
  106031. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  106032. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  106033. */
  106034. get: function () {
  106035. return this._primaryColorShadowLevel;
  106036. },
  106037. set: function (value) {
  106038. this._primaryColorShadowLevel = value;
  106039. this._computePrimaryColors();
  106040. this._markAllSubMeshesAsLightsDirty();
  106041. },
  106042. enumerable: true,
  106043. configurable: true
  106044. });
  106045. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  106046. /**
  106047. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  106048. * The primary color is used at the level chosen to define what the white area would look.
  106049. */
  106050. get: function () {
  106051. return this._primaryColorHighlightLevel;
  106052. },
  106053. set: function (value) {
  106054. this._primaryColorHighlightLevel = value;
  106055. this._computePrimaryColors();
  106056. this._markAllSubMeshesAsLightsDirty();
  106057. },
  106058. enumerable: true,
  106059. configurable: true
  106060. });
  106061. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  106062. /**
  106063. * Sets the reflection reflectance fresnel values according to the default standard
  106064. * empirically know to work well :-)
  106065. */
  106066. set: function (value) {
  106067. var reflectionWeight = value;
  106068. if (reflectionWeight < 0.5) {
  106069. reflectionWeight = reflectionWeight * 2.0;
  106070. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  106071. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  106072. }
  106073. else {
  106074. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  106075. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  106076. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  106077. }
  106078. },
  106079. enumerable: true,
  106080. configurable: true
  106081. });
  106082. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  106083. /**
  106084. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106085. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  106086. * Recommended to be keep at 1.0 except for special cases.
  106087. */
  106088. get: function () {
  106089. return this._fovMultiplier;
  106090. },
  106091. set: function (value) {
  106092. if (isNaN(value)) {
  106093. value = 1.0;
  106094. }
  106095. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  106096. },
  106097. enumerable: true,
  106098. configurable: true
  106099. });
  106100. /**
  106101. * Attaches a new image processing configuration to the PBR Material.
  106102. * @param configuration (if null the scene configuration will be use)
  106103. */
  106104. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  106105. var _this = this;
  106106. if (configuration === this._imageProcessingConfiguration) {
  106107. return;
  106108. }
  106109. // Detaches observer.
  106110. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106111. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106112. }
  106113. // Pick the scene configuration if needed.
  106114. if (!configuration) {
  106115. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  106116. }
  106117. else {
  106118. this._imageProcessingConfiguration = configuration;
  106119. }
  106120. // Attaches observer.
  106121. if (this._imageProcessingConfiguration) {
  106122. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  106123. _this._computePrimaryColorFromPerceptualColor();
  106124. _this._markAllSubMeshesAsImageProcessingDirty();
  106125. });
  106126. }
  106127. };
  106128. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  106129. /**
  106130. * Gets the image processing configuration used either in this material.
  106131. */
  106132. get: function () {
  106133. return this._imageProcessingConfiguration;
  106134. },
  106135. /**
  106136. * Sets the Default image processing configuration used either in the this material.
  106137. *
  106138. * If sets to null, the scene one is in use.
  106139. */
  106140. set: function (value) {
  106141. this._attachImageProcessingConfiguration(value);
  106142. // Ensure the effect will be rebuilt.
  106143. this._markAllSubMeshesAsTexturesDirty();
  106144. },
  106145. enumerable: true,
  106146. configurable: true
  106147. });
  106148. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  106149. /**
  106150. * Gets wether the color curves effect is enabled.
  106151. */
  106152. get: function () {
  106153. return this.imageProcessingConfiguration.colorCurvesEnabled;
  106154. },
  106155. /**
  106156. * Sets wether the color curves effect is enabled.
  106157. */
  106158. set: function (value) {
  106159. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  106160. },
  106161. enumerable: true,
  106162. configurable: true
  106163. });
  106164. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  106165. /**
  106166. * Gets wether the color grading effect is enabled.
  106167. */
  106168. get: function () {
  106169. return this.imageProcessingConfiguration.colorGradingEnabled;
  106170. },
  106171. /**
  106172. * Gets wether the color grading effect is enabled.
  106173. */
  106174. set: function (value) {
  106175. this.imageProcessingConfiguration.colorGradingEnabled = value;
  106176. },
  106177. enumerable: true,
  106178. configurable: true
  106179. });
  106180. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  106181. /**
  106182. * Gets wether tonemapping is enabled or not.
  106183. */
  106184. get: function () {
  106185. return this._imageProcessingConfiguration.toneMappingEnabled;
  106186. },
  106187. /**
  106188. * Sets wether tonemapping is enabled or not
  106189. */
  106190. set: function (value) {
  106191. this._imageProcessingConfiguration.toneMappingEnabled = value;
  106192. },
  106193. enumerable: true,
  106194. configurable: true
  106195. });
  106196. ;
  106197. ;
  106198. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  106199. /**
  106200. * The camera exposure used on this material.
  106201. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  106202. * This corresponds to a photographic exposure.
  106203. */
  106204. get: function () {
  106205. return this._imageProcessingConfiguration.exposure;
  106206. },
  106207. /**
  106208. * The camera exposure used on this material.
  106209. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  106210. * This corresponds to a photographic exposure.
  106211. */
  106212. set: function (value) {
  106213. this._imageProcessingConfiguration.exposure = value;
  106214. },
  106215. enumerable: true,
  106216. configurable: true
  106217. });
  106218. ;
  106219. ;
  106220. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  106221. /**
  106222. * Gets The camera contrast used on this material.
  106223. */
  106224. get: function () {
  106225. return this._imageProcessingConfiguration.contrast;
  106226. },
  106227. /**
  106228. * Sets The camera contrast used on this material.
  106229. */
  106230. set: function (value) {
  106231. this._imageProcessingConfiguration.contrast = value;
  106232. },
  106233. enumerable: true,
  106234. configurable: true
  106235. });
  106236. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  106237. /**
  106238. * Gets the Color Grading 2D Lookup Texture.
  106239. */
  106240. get: function () {
  106241. return this._imageProcessingConfiguration.colorGradingTexture;
  106242. },
  106243. /**
  106244. * Sets the Color Grading 2D Lookup Texture.
  106245. */
  106246. set: function (value) {
  106247. this.imageProcessingConfiguration.colorGradingTexture = value;
  106248. },
  106249. enumerable: true,
  106250. configurable: true
  106251. });
  106252. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  106253. /**
  106254. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  106255. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  106256. * 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;
  106257. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  106258. */
  106259. get: function () {
  106260. return this.imageProcessingConfiguration.colorCurves;
  106261. },
  106262. /**
  106263. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  106264. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  106265. * 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;
  106266. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  106267. */
  106268. set: function (value) {
  106269. this.imageProcessingConfiguration.colorCurves = value;
  106270. },
  106271. enumerable: true,
  106272. configurable: true
  106273. });
  106274. /**
  106275. * The entire material has been created in order to prevent overdraw.
  106276. * @returns false
  106277. */
  106278. BackgroundMaterial.prototype.needAlphaTesting = function () {
  106279. return true;
  106280. };
  106281. /**
  106282. * The entire material has been created in order to prevent overdraw.
  106283. * @returns true if blending is enable
  106284. */
  106285. BackgroundMaterial.prototype.needAlphaBlending = function () {
  106286. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  106287. };
  106288. /**
  106289. * Checks wether the material is ready to be rendered for a given mesh.
  106290. * @param mesh The mesh to render
  106291. * @param subMesh The submesh to check against
  106292. * @param useInstances Specify wether or not the material is used with instances
  106293. * @returns true if all the dependencies are ready (Textures, Effects...)
  106294. */
  106295. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  106296. var _this = this;
  106297. if (useInstances === void 0) { useInstances = false; }
  106298. if (subMesh.effect && this.isFrozen) {
  106299. if (this._wasPreviouslyReady) {
  106300. return true;
  106301. }
  106302. }
  106303. if (!subMesh._materialDefines) {
  106304. subMesh._materialDefines = new BackgroundMaterialDefines();
  106305. }
  106306. var scene = this.getScene();
  106307. var defines = subMesh._materialDefines;
  106308. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  106309. if (defines._renderId === scene.getRenderId()) {
  106310. return true;
  106311. }
  106312. }
  106313. var engine = scene.getEngine();
  106314. // Lights
  106315. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  106316. defines._needNormals = true;
  106317. // Textures
  106318. if (defines._areTexturesDirty) {
  106319. defines._needUVs = false;
  106320. if (scene.texturesEnabled) {
  106321. if (scene.getEngine().getCaps().textureLOD) {
  106322. defines.TEXTURELODSUPPORT = true;
  106323. }
  106324. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106325. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  106326. return false;
  106327. }
  106328. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  106329. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  106330. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  106331. defines.OPACITYFRESNEL = this._opacityFresnel;
  106332. }
  106333. else {
  106334. defines.DIFFUSE = false;
  106335. defines.DIFFUSEHASALPHA = false;
  106336. defines.GAMMADIFFUSE = false;
  106337. defines.OPACITYFRESNEL = false;
  106338. }
  106339. var reflectionTexture = this._reflectionTexture;
  106340. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106341. if (!reflectionTexture.isReadyOrNotBlocking()) {
  106342. return false;
  106343. }
  106344. defines.REFLECTION = true;
  106345. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  106346. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  106347. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  106348. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  106349. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  106350. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  106351. defines.REFLECTIONBGR = this.switchToBGR;
  106352. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  106353. defines.INVERTCUBICMAP = true;
  106354. }
  106355. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  106356. switch (reflectionTexture.coordinatesMode) {
  106357. case BABYLON.Texture.EXPLICIT_MODE:
  106358. defines.REFLECTIONMAP_EXPLICIT = true;
  106359. break;
  106360. case BABYLON.Texture.PLANAR_MODE:
  106361. defines.REFLECTIONMAP_PLANAR = true;
  106362. break;
  106363. case BABYLON.Texture.PROJECTION_MODE:
  106364. defines.REFLECTIONMAP_PROJECTION = true;
  106365. break;
  106366. case BABYLON.Texture.SKYBOX_MODE:
  106367. defines.REFLECTIONMAP_SKYBOX = true;
  106368. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  106369. break;
  106370. case BABYLON.Texture.SPHERICAL_MODE:
  106371. defines.REFLECTIONMAP_SPHERICAL = true;
  106372. break;
  106373. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  106374. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  106375. break;
  106376. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  106377. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  106378. break;
  106379. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  106380. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  106381. break;
  106382. case BABYLON.Texture.CUBIC_MODE:
  106383. case BABYLON.Texture.INVCUBIC_MODE:
  106384. default:
  106385. defines.REFLECTIONMAP_CUBIC = true;
  106386. break;
  106387. }
  106388. if (this.reflectionFresnel) {
  106389. defines.REFLECTIONFRESNEL = true;
  106390. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  106391. this._reflectionControls.x = this.reflectionAmount;
  106392. this._reflectionControls.y = this.reflectionReflectance0;
  106393. this._reflectionControls.z = this.reflectionReflectance90;
  106394. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  106395. }
  106396. else {
  106397. defines.REFLECTIONFRESNEL = false;
  106398. defines.REFLECTIONFALLOFF = false;
  106399. }
  106400. }
  106401. else {
  106402. defines.REFLECTION = false;
  106403. defines.REFLECTIONFRESNEL = false;
  106404. defines.REFLECTIONFALLOFF = false;
  106405. defines.REFLECTIONBLUR = false;
  106406. defines.REFLECTIONMAP_3D = false;
  106407. defines.REFLECTIONMAP_SPHERICAL = false;
  106408. defines.REFLECTIONMAP_PLANAR = false;
  106409. defines.REFLECTIONMAP_CUBIC = false;
  106410. defines.REFLECTIONMAP_PROJECTION = false;
  106411. defines.REFLECTIONMAP_SKYBOX = false;
  106412. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106413. defines.REFLECTIONMAP_EXPLICIT = false;
  106414. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106415. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106416. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106417. defines.INVERTCUBICMAP = false;
  106418. defines.REFLECTIONMAP_OPPOSITEZ = false;
  106419. defines.LODINREFLECTIONALPHA = false;
  106420. defines.GAMMAREFLECTION = false;
  106421. defines.RGBDREFLECTION = false;
  106422. }
  106423. }
  106424. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  106425. defines.USERGBCOLOR = this._useRGBColor;
  106426. defines.NOISE = this._enableNoise;
  106427. }
  106428. if (defines._areLightsDirty) {
  106429. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  106430. }
  106431. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  106432. if (!this._imageProcessingConfiguration.isReady()) {
  106433. return false;
  106434. }
  106435. this._imageProcessingConfiguration.prepareDefines(defines);
  106436. }
  106437. // Misc.
  106438. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  106439. // Values that need to be evaluated on every frame
  106440. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  106441. // Attribs
  106442. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  106443. if (mesh) {
  106444. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  106445. mesh.createNormals(true);
  106446. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  106447. }
  106448. }
  106449. }
  106450. // Get correct effect
  106451. if (defines.isDirty) {
  106452. defines.markAsProcessed();
  106453. scene.resetCachedMaterial();
  106454. // Fallbacks
  106455. var fallbacks = new BABYLON.EffectFallbacks();
  106456. if (defines.FOG) {
  106457. fallbacks.addFallback(0, "FOG");
  106458. }
  106459. if (defines.POINTSIZE) {
  106460. fallbacks.addFallback(1, "POINTSIZE");
  106461. }
  106462. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  106463. if (defines.NUM_BONE_INFLUENCERS > 0) {
  106464. fallbacks.addCPUSkinningFallback(0, mesh);
  106465. }
  106466. //Attributes
  106467. var attribs = [BABYLON.VertexBuffer.PositionKind];
  106468. if (defines.NORMAL) {
  106469. attribs.push(BABYLON.VertexBuffer.NormalKind);
  106470. }
  106471. if (defines.UV1) {
  106472. attribs.push(BABYLON.VertexBuffer.UVKind);
  106473. }
  106474. if (defines.UV2) {
  106475. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106476. }
  106477. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  106478. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  106479. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  106480. "vFogInfos", "vFogColor", "pointSize",
  106481. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  106482. "vPrimaryColor", "vPrimaryColorShadow",
  106483. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  106484. "shadowLevel", "alpha",
  106485. "vBackgroundCenter", "vReflectionControl",
  106486. "vDiffuseInfos", "diffuseMatrix",
  106487. ];
  106488. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  106489. var uniformBuffers = ["Material", "Scene"];
  106490. if (BABYLON.ImageProcessingConfiguration) {
  106491. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  106492. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  106493. }
  106494. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  106495. uniformsNames: uniforms,
  106496. uniformBuffersNames: uniformBuffers,
  106497. samplers: samplers,
  106498. defines: defines,
  106499. maxSimultaneousLights: this._maxSimultaneousLights
  106500. });
  106501. var onCompiled = function (effect) {
  106502. if (_this.onCompiled) {
  106503. _this.onCompiled(effect);
  106504. }
  106505. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  106506. };
  106507. var join = defines.toString();
  106508. subMesh.setEffect(scene.getEngine().createEffect("background", {
  106509. attributes: attribs,
  106510. uniformsNames: uniforms,
  106511. uniformBuffersNames: uniformBuffers,
  106512. samplers: samplers,
  106513. defines: join,
  106514. fallbacks: fallbacks,
  106515. onCompiled: onCompiled,
  106516. onError: this.onError,
  106517. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  106518. }, engine), defines);
  106519. this.buildUniformLayout();
  106520. }
  106521. if (!subMesh.effect || !subMesh.effect.isReady()) {
  106522. return false;
  106523. }
  106524. defines._renderId = scene.getRenderId();
  106525. this._wasPreviouslyReady = true;
  106526. return true;
  106527. };
  106528. /**
  106529. * Compute the primary color according to the chosen perceptual color.
  106530. */
  106531. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  106532. if (!this.__perceptualColor) {
  106533. return;
  106534. }
  106535. this._primaryColor.copyFrom(this.__perceptualColor);
  106536. // Revert gamma space.
  106537. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  106538. // Revert image processing configuration.
  106539. if (this._imageProcessingConfiguration) {
  106540. // Revert Exposure.
  106541. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  106542. }
  106543. this._computePrimaryColors();
  106544. };
  106545. /**
  106546. * Compute the highlights and shadow colors according to their chosen levels.
  106547. */
  106548. BackgroundMaterial.prototype._computePrimaryColors = function () {
  106549. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  106550. return;
  106551. }
  106552. // Find the highlight color based on the configuration.
  106553. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  106554. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  106555. // Find the shadow color based on the configuration.
  106556. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  106557. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  106558. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  106559. };
  106560. /**
  106561. * Build the uniform buffer used in the material.
  106562. */
  106563. BackgroundMaterial.prototype.buildUniformLayout = function () {
  106564. // Order is important !
  106565. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  106566. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  106567. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  106568. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  106569. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  106570. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  106571. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  106572. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  106573. this._uniformBuffer.addUniform("pointSize", 1);
  106574. this._uniformBuffer.addUniform("shadowLevel", 1);
  106575. this._uniformBuffer.addUniform("alpha", 1);
  106576. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  106577. this._uniformBuffer.addUniform("vReflectionControl", 4);
  106578. this._uniformBuffer.create();
  106579. };
  106580. /**
  106581. * Unbind the material.
  106582. */
  106583. BackgroundMaterial.prototype.unbind = function () {
  106584. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  106585. this._uniformBuffer.setTexture("diffuseSampler", null);
  106586. }
  106587. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  106588. this._uniformBuffer.setTexture("reflectionSampler", null);
  106589. }
  106590. _super.prototype.unbind.call(this);
  106591. };
  106592. /**
  106593. * Bind only the world matrix to the material.
  106594. * @param world The world matrix to bind.
  106595. */
  106596. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  106597. this._activeEffect.setMatrix("world", world);
  106598. };
  106599. /**
  106600. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  106601. * @param world The world matrix to bind.
  106602. * @param subMesh The submesh to bind for.
  106603. */
  106604. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  106605. var scene = this.getScene();
  106606. var defines = subMesh._materialDefines;
  106607. if (!defines) {
  106608. return;
  106609. }
  106610. var effect = subMesh.effect;
  106611. if (!effect) {
  106612. return;
  106613. }
  106614. this._activeEffect = effect;
  106615. // Matrices
  106616. this.bindOnlyWorldMatrix(world);
  106617. // Bones
  106618. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  106619. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  106620. if (mustRebind) {
  106621. this._uniformBuffer.bindToEffect(effect, "Material");
  106622. this.bindViewProjection(effect);
  106623. var reflectionTexture = this._reflectionTexture;
  106624. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  106625. // Texture uniforms
  106626. if (scene.texturesEnabled) {
  106627. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106628. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  106629. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  106630. }
  106631. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106632. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  106633. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  106634. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  106635. }
  106636. }
  106637. if (this.shadowLevel > 0) {
  106638. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  106639. }
  106640. this._uniformBuffer.updateFloat("alpha", this.alpha);
  106641. // Point size
  106642. if (this.pointsCloud) {
  106643. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  106644. }
  106645. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  106646. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  106647. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  106648. }
  106649. else {
  106650. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  106651. }
  106652. }
  106653. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  106654. // Textures
  106655. if (scene.texturesEnabled) {
  106656. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106657. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  106658. }
  106659. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106660. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  106661. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106662. }
  106663. else if (!defines.REFLECTIONBLUR) {
  106664. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106665. }
  106666. else {
  106667. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  106668. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  106669. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  106670. }
  106671. if (defines.REFLECTIONFRESNEL) {
  106672. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  106673. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  106674. }
  106675. }
  106676. }
  106677. // Clip plane
  106678. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  106679. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  106680. }
  106681. if (mustRebind || !this.isFrozen) {
  106682. if (scene.lightsEnabled) {
  106683. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  106684. }
  106685. // View
  106686. this.bindView(effect);
  106687. // Fog
  106688. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  106689. // image processing
  106690. if (this._imageProcessingConfiguration) {
  106691. this._imageProcessingConfiguration.bind(this._activeEffect);
  106692. }
  106693. }
  106694. this._uniformBuffer.update();
  106695. this._afterBind(mesh, this._activeEffect);
  106696. };
  106697. /**
  106698. * Dispose the material.
  106699. * @param forceDisposeEffect Force disposal of the associated effect.
  106700. * @param forceDisposeTextures Force disposal of the associated textures.
  106701. */
  106702. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  106703. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  106704. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  106705. if (forceDisposeTextures) {
  106706. if (this.diffuseTexture) {
  106707. this.diffuseTexture.dispose();
  106708. }
  106709. if (this.reflectionTexture) {
  106710. this.reflectionTexture.dispose();
  106711. }
  106712. }
  106713. this._renderTargets.dispose();
  106714. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106715. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106716. }
  106717. _super.prototype.dispose.call(this, forceDisposeEffect);
  106718. };
  106719. /**
  106720. * Clones the material.
  106721. * @param name The cloned name.
  106722. * @returns The cloned material.
  106723. */
  106724. BackgroundMaterial.prototype.clone = function (name) {
  106725. var _this = this;
  106726. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  106727. };
  106728. /**
  106729. * Serializes the current material to its JSON representation.
  106730. * @returns The JSON representation.
  106731. */
  106732. BackgroundMaterial.prototype.serialize = function () {
  106733. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106734. serializationObject.customType = "BABYLON.BackgroundMaterial";
  106735. return serializationObject;
  106736. };
  106737. /**
  106738. * Gets the class name of the material
  106739. * @returns "BackgroundMaterial"
  106740. */
  106741. BackgroundMaterial.prototype.getClassName = function () {
  106742. return "BackgroundMaterial";
  106743. };
  106744. /**
  106745. * Parse a JSON input to create back a background material.
  106746. * @param source The JSON data to parse
  106747. * @param scene The scene to create the parsed material in
  106748. * @param rootUrl The root url of the assets the material depends upon
  106749. * @returns the instantiated BackgroundMaterial.
  106750. */
  106751. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  106752. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  106753. };
  106754. /**
  106755. * Standard reflectance value at parallel view angle.
  106756. */
  106757. BackgroundMaterial.StandardReflectance0 = 0.05;
  106758. /**
  106759. * Standard reflectance value at grazing angle.
  106760. */
  106761. BackgroundMaterial.StandardReflectance90 = 0.5;
  106762. __decorate([
  106763. BABYLON.serializeAsColor3()
  106764. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  106765. __decorate([
  106766. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106767. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  106768. __decorate([
  106769. BABYLON.serializeAsColor3()
  106770. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  106771. __decorate([
  106772. BABYLON.serialize()
  106773. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  106774. __decorate([
  106775. BABYLON.serialize()
  106776. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  106777. __decorate([
  106778. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106779. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  106780. __decorate([
  106781. BABYLON.serializeAsTexture()
  106782. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  106783. __decorate([
  106784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106785. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  106786. __decorate([
  106787. BABYLON.serialize()
  106788. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  106789. __decorate([
  106790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106791. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  106792. __decorate([
  106793. BABYLON.serializeAsTexture()
  106794. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  106795. __decorate([
  106796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106797. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  106798. __decorate([
  106799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106800. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  106801. __decorate([
  106802. BABYLON.serialize()
  106803. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  106804. __decorate([
  106805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106806. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  106807. __decorate([
  106808. BABYLON.serializeAsVector3()
  106809. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  106810. __decorate([
  106811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106812. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  106813. __decorate([
  106814. BABYLON.serialize()
  106815. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  106816. __decorate([
  106817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106818. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  106819. __decorate([
  106820. BABYLON.serialize()
  106821. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  106822. __decorate([
  106823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106824. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  106825. __decorate([
  106826. BABYLON.serialize()
  106827. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  106828. __decorate([
  106829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106830. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  106831. __decorate([
  106832. BABYLON.serialize()
  106833. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  106834. __decorate([
  106835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106836. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  106837. __decorate([
  106838. BABYLON.serialize()
  106839. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  106840. __decorate([
  106841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106842. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  106843. __decorate([
  106844. BABYLON.serialize()
  106845. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  106846. __decorate([
  106847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106848. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  106849. __decorate([
  106850. BABYLON.serialize()
  106851. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  106852. __decorate([
  106853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106854. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  106855. __decorate([
  106856. BABYLON.serialize()
  106857. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  106858. __decorate([
  106859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106860. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  106861. __decorate([
  106862. BABYLON.serialize()
  106863. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  106864. __decorate([
  106865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106866. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  106867. __decorate([
  106868. BABYLON.serializeAsImageProcessingConfiguration()
  106869. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  106870. return BackgroundMaterial;
  106871. }(BABYLON.PushMaterial));
  106872. BABYLON.BackgroundMaterial = BackgroundMaterial;
  106873. })(BABYLON || (BABYLON = {}));
  106874. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  106875. var __assign = (this && this.__assign) || function () {
  106876. __assign = Object.assign || function(t) {
  106877. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106878. s = arguments[i];
  106879. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106880. t[p] = s[p];
  106881. }
  106882. return t;
  106883. };
  106884. return __assign.apply(this, arguments);
  106885. };
  106886. var BABYLON;
  106887. (function (BABYLON) {
  106888. /**
  106889. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  106890. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  106891. * It also helps with the default setup of your imageProcessing configuration.
  106892. */
  106893. var EnvironmentHelper = /** @class */ (function () {
  106894. /**
  106895. * constructor
  106896. * @param options
  106897. * @param scene The scene to add the material to
  106898. */
  106899. function EnvironmentHelper(options, scene) {
  106900. var _this = this;
  106901. this._errorHandler = function (message, exception) {
  106902. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  106903. };
  106904. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  106905. this._scene = scene;
  106906. this.onErrorObservable = new BABYLON.Observable();
  106907. this._setupBackground();
  106908. this._setupImageProcessing();
  106909. }
  106910. /**
  106911. * Creates the default options for the helper.
  106912. */
  106913. EnvironmentHelper._getDefaultOptions = function () {
  106914. return {
  106915. createGround: true,
  106916. groundSize: 15,
  106917. groundTexture: this._groundTextureCDNUrl,
  106918. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106919. groundOpacity: 0.9,
  106920. enableGroundShadow: true,
  106921. groundShadowLevel: 0.5,
  106922. enableGroundMirror: false,
  106923. groundMirrorSizeRatio: 0.3,
  106924. groundMirrorBlurKernel: 64,
  106925. groundMirrorAmount: 1,
  106926. groundMirrorFresnelWeight: 1,
  106927. groundMirrorFallOffDistance: 0,
  106928. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  106929. groundYBias: 0.00001,
  106930. createSkybox: true,
  106931. skyboxSize: 20,
  106932. skyboxTexture: this._skyboxTextureCDNUrl,
  106933. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106934. backgroundYRotation: 0,
  106935. sizeAuto: true,
  106936. rootPosition: BABYLON.Vector3.Zero(),
  106937. setupImageProcessing: true,
  106938. environmentTexture: this._environmentTextureCDNUrl,
  106939. cameraExposure: 0.8,
  106940. cameraContrast: 1.2,
  106941. toneMappingEnabled: true,
  106942. };
  106943. };
  106944. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  106945. /**
  106946. * Gets the root mesh created by the helper.
  106947. */
  106948. get: function () {
  106949. return this._rootMesh;
  106950. },
  106951. enumerable: true,
  106952. configurable: true
  106953. });
  106954. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  106955. /**
  106956. * Gets the skybox created by the helper.
  106957. */
  106958. get: function () {
  106959. return this._skybox;
  106960. },
  106961. enumerable: true,
  106962. configurable: true
  106963. });
  106964. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  106965. /**
  106966. * Gets the skybox texture created by the helper.
  106967. */
  106968. get: function () {
  106969. return this._skyboxTexture;
  106970. },
  106971. enumerable: true,
  106972. configurable: true
  106973. });
  106974. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  106975. /**
  106976. * Gets the skybox material created by the helper.
  106977. */
  106978. get: function () {
  106979. return this._skyboxMaterial;
  106980. },
  106981. enumerable: true,
  106982. configurable: true
  106983. });
  106984. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  106985. /**
  106986. * Gets the ground mesh created by the helper.
  106987. */
  106988. get: function () {
  106989. return this._ground;
  106990. },
  106991. enumerable: true,
  106992. configurable: true
  106993. });
  106994. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  106995. /**
  106996. * Gets the ground texture created by the helper.
  106997. */
  106998. get: function () {
  106999. return this._groundTexture;
  107000. },
  107001. enumerable: true,
  107002. configurable: true
  107003. });
  107004. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  107005. /**
  107006. * Gets the ground mirror created by the helper.
  107007. */
  107008. get: function () {
  107009. return this._groundMirror;
  107010. },
  107011. enumerable: true,
  107012. configurable: true
  107013. });
  107014. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  107015. /**
  107016. * Gets the ground mirror render list to helps pushing the meshes
  107017. * you wish in the ground reflection.
  107018. */
  107019. get: function () {
  107020. if (this._groundMirror) {
  107021. return this._groundMirror.renderList;
  107022. }
  107023. return null;
  107024. },
  107025. enumerable: true,
  107026. configurable: true
  107027. });
  107028. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  107029. /**
  107030. * Gets the ground material created by the helper.
  107031. */
  107032. get: function () {
  107033. return this._groundMaterial;
  107034. },
  107035. enumerable: true,
  107036. configurable: true
  107037. });
  107038. /**
  107039. * Updates the background according to the new options
  107040. * @param options
  107041. */
  107042. EnvironmentHelper.prototype.updateOptions = function (options) {
  107043. var newOptions = __assign({}, this._options, options);
  107044. if (this._ground && !newOptions.createGround) {
  107045. this._ground.dispose();
  107046. this._ground = null;
  107047. }
  107048. if (this._groundMaterial && !newOptions.createGround) {
  107049. this._groundMaterial.dispose();
  107050. this._groundMaterial = null;
  107051. }
  107052. if (this._groundTexture) {
  107053. if (this._options.groundTexture != newOptions.groundTexture) {
  107054. this._groundTexture.dispose();
  107055. this._groundTexture = null;
  107056. }
  107057. }
  107058. if (this._skybox && !newOptions.createSkybox) {
  107059. this._skybox.dispose();
  107060. this._skybox = null;
  107061. }
  107062. if (this._skyboxMaterial && !newOptions.createSkybox) {
  107063. this._skyboxMaterial.dispose();
  107064. this._skyboxMaterial = null;
  107065. }
  107066. if (this._skyboxTexture) {
  107067. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  107068. this._skyboxTexture.dispose();
  107069. this._skyboxTexture = null;
  107070. }
  107071. }
  107072. if (this._groundMirror && !newOptions.enableGroundMirror) {
  107073. this._groundMirror.dispose();
  107074. this._groundMirror = null;
  107075. }
  107076. if (this._scene.environmentTexture) {
  107077. if (this._options.environmentTexture != newOptions.environmentTexture) {
  107078. this._scene.environmentTexture.dispose();
  107079. }
  107080. }
  107081. this._options = newOptions;
  107082. this._setupBackground();
  107083. this._setupImageProcessing();
  107084. };
  107085. /**
  107086. * Sets the primary color of all the available elements.
  107087. * @param color the main color to affect to the ground and the background
  107088. */
  107089. EnvironmentHelper.prototype.setMainColor = function (color) {
  107090. if (this.groundMaterial) {
  107091. this.groundMaterial.primaryColor = color;
  107092. }
  107093. if (this.skyboxMaterial) {
  107094. this.skyboxMaterial.primaryColor = color;
  107095. }
  107096. if (this.groundMirror) {
  107097. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  107098. }
  107099. };
  107100. /**
  107101. * Setup the image processing according to the specified options.
  107102. */
  107103. EnvironmentHelper.prototype._setupImageProcessing = function () {
  107104. if (this._options.setupImageProcessing) {
  107105. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  107106. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  107107. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  107108. this._setupEnvironmentTexture();
  107109. }
  107110. };
  107111. /**
  107112. * Setup the environment texture according to the specified options.
  107113. */
  107114. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  107115. if (this._scene.environmentTexture) {
  107116. return;
  107117. }
  107118. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  107119. this._scene.environmentTexture = this._options.environmentTexture;
  107120. return;
  107121. }
  107122. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  107123. this._scene.environmentTexture = environmentTexture;
  107124. };
  107125. /**
  107126. * Setup the background according to the specified options.
  107127. */
  107128. EnvironmentHelper.prototype._setupBackground = function () {
  107129. if (!this._rootMesh) {
  107130. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  107131. }
  107132. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  107133. var sceneSize = this._getSceneSize();
  107134. if (this._options.createGround) {
  107135. this._setupGround(sceneSize);
  107136. this._setupGroundMaterial();
  107137. this._setupGroundDiffuseTexture();
  107138. if (this._options.enableGroundMirror) {
  107139. this._setupGroundMirrorTexture(sceneSize);
  107140. }
  107141. this._setupMirrorInGroundMaterial();
  107142. }
  107143. if (this._options.createSkybox) {
  107144. this._setupSkybox(sceneSize);
  107145. this._setupSkyboxMaterial();
  107146. this._setupSkyboxReflectionTexture();
  107147. }
  107148. this._rootMesh.position.x = sceneSize.rootPosition.x;
  107149. this._rootMesh.position.z = sceneSize.rootPosition.z;
  107150. this._rootMesh.position.y = sceneSize.rootPosition.y;
  107151. };
  107152. /**
  107153. * Get the scene sizes according to the setup.
  107154. */
  107155. EnvironmentHelper.prototype._getSceneSize = function () {
  107156. var _this = this;
  107157. var groundSize = this._options.groundSize;
  107158. var skyboxSize = this._options.skyboxSize;
  107159. var rootPosition = this._options.rootPosition;
  107160. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  107161. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  107162. }
  107163. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  107164. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  107165. });
  107166. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  107167. if (this._options.sizeAuto) {
  107168. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  107169. this._scene.activeCamera.upperRadiusLimit) {
  107170. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  107171. skyboxSize = groundSize;
  107172. }
  107173. var sceneDiagonalLenght = sceneDiagonal.length();
  107174. if (sceneDiagonalLenght > groundSize) {
  107175. groundSize = sceneDiagonalLenght * 2;
  107176. skyboxSize = groundSize;
  107177. }
  107178. // 10 % bigger.
  107179. groundSize *= 1.1;
  107180. skyboxSize *= 1.5;
  107181. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  107182. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  107183. }
  107184. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  107185. };
  107186. /**
  107187. * Setup the ground according to the specified options.
  107188. */
  107189. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  107190. var _this = this;
  107191. if (!this._ground || this._ground.isDisposed()) {
  107192. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  107193. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  107194. this._ground.parent = this._rootMesh;
  107195. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  107196. }
  107197. this._ground.receiveShadows = this._options.enableGroundShadow;
  107198. };
  107199. /**
  107200. * Setup the ground material according to the specified options.
  107201. */
  107202. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  107203. if (!this._groundMaterial) {
  107204. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  107205. }
  107206. this._groundMaterial.alpha = this._options.groundOpacity;
  107207. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  107208. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  107209. this._groundMaterial.primaryColor = this._options.groundColor;
  107210. this._groundMaterial.useRGBColor = false;
  107211. this._groundMaterial.enableNoise = true;
  107212. if (this._ground) {
  107213. this._ground.material = this._groundMaterial;
  107214. }
  107215. };
  107216. /**
  107217. * Setup the ground diffuse texture according to the specified options.
  107218. */
  107219. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  107220. if (!this._groundMaterial) {
  107221. return;
  107222. }
  107223. if (this._groundTexture) {
  107224. return;
  107225. }
  107226. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  107227. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  107228. return;
  107229. }
  107230. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  107231. diffuseTexture.gammaSpace = false;
  107232. diffuseTexture.hasAlpha = true;
  107233. this._groundMaterial.diffuseTexture = diffuseTexture;
  107234. };
  107235. /**
  107236. * Setup the ground mirror texture according to the specified options.
  107237. */
  107238. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  107239. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107240. if (!this._groundMirror) {
  107241. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  107242. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  107243. this._groundMirror.anisotropicFilteringLevel = 1;
  107244. this._groundMirror.wrapU = wrapping;
  107245. this._groundMirror.wrapV = wrapping;
  107246. this._groundMirror.gammaSpace = false;
  107247. if (this._groundMirror.renderList) {
  107248. for (var i = 0; i < this._scene.meshes.length; i++) {
  107249. var mesh = this._scene.meshes[i];
  107250. if (mesh !== this._ground &&
  107251. mesh !== this._skybox &&
  107252. mesh !== this._rootMesh) {
  107253. this._groundMirror.renderList.push(mesh);
  107254. }
  107255. }
  107256. }
  107257. }
  107258. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  107259. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  107260. };
  107261. /**
  107262. * Setup the ground to receive the mirror texture.
  107263. */
  107264. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  107265. if (this._groundMaterial) {
  107266. this._groundMaterial.reflectionTexture = this._groundMirror;
  107267. this._groundMaterial.reflectionFresnel = true;
  107268. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  107269. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  107270. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  107271. }
  107272. };
  107273. /**
  107274. * Setup the skybox according to the specified options.
  107275. */
  107276. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  107277. var _this = this;
  107278. if (!this._skybox || this._skybox.isDisposed()) {
  107279. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  107280. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  107281. }
  107282. this._skybox.parent = this._rootMesh;
  107283. };
  107284. /**
  107285. * Setup the skybox material according to the specified options.
  107286. */
  107287. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  107288. if (!this._skybox) {
  107289. return;
  107290. }
  107291. if (!this._skyboxMaterial) {
  107292. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  107293. }
  107294. this._skyboxMaterial.useRGBColor = false;
  107295. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  107296. this._skyboxMaterial.enableNoise = true;
  107297. this._skybox.material = this._skyboxMaterial;
  107298. };
  107299. /**
  107300. * Setup the skybox reflection texture according to the specified options.
  107301. */
  107302. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  107303. if (!this._skyboxMaterial) {
  107304. return;
  107305. }
  107306. if (this._skyboxTexture) {
  107307. return;
  107308. }
  107309. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  107310. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  107311. return;
  107312. }
  107313. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  107314. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  107315. this._skyboxTexture.gammaSpace = false;
  107316. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  107317. };
  107318. /**
  107319. * Dispose all the elements created by the Helper.
  107320. */
  107321. EnvironmentHelper.prototype.dispose = function () {
  107322. if (this._groundMaterial) {
  107323. this._groundMaterial.dispose(true, true);
  107324. }
  107325. if (this._skyboxMaterial) {
  107326. this._skyboxMaterial.dispose(true, true);
  107327. }
  107328. this._rootMesh.dispose(false);
  107329. };
  107330. /**
  107331. * Default ground texture URL.
  107332. */
  107333. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  107334. /**
  107335. * Default skybox texture URL.
  107336. */
  107337. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  107338. /**
  107339. * Default environment texture URL.
  107340. */
  107341. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  107342. return EnvironmentHelper;
  107343. }());
  107344. BABYLON.EnvironmentHelper = EnvironmentHelper;
  107345. })(BABYLON || (BABYLON = {}));
  107346. //# sourceMappingURL=babylon.environmentHelper.js.map
  107347. var BABYLON;
  107348. (function (BABYLON) {
  107349. /** Internal class used to store shapes for emitters */
  107350. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  107351. function ParticleSystemSetEmitterCreationOptions() {
  107352. }
  107353. return ParticleSystemSetEmitterCreationOptions;
  107354. }());
  107355. /**
  107356. * Represents a set of particle systems working together to create a specific effect
  107357. */
  107358. var ParticleSystemSet = /** @class */ (function () {
  107359. function ParticleSystemSet() {
  107360. /**
  107361. * Gets the particle system list
  107362. */
  107363. this.systems = new Array();
  107364. }
  107365. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  107366. /**
  107367. * Gets the emitter node used with this set
  107368. */
  107369. get: function () {
  107370. return this._emitterNode;
  107371. },
  107372. enumerable: true,
  107373. configurable: true
  107374. });
  107375. /**
  107376. * Creates a new emitter mesh as a sphere
  107377. * @param options defines the options used to create the sphere
  107378. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  107379. * @param scene defines the hosting scene
  107380. */
  107381. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  107382. if (this._emitterNode) {
  107383. this._emitterNode.dispose();
  107384. }
  107385. this._emitterCreationOptions = {
  107386. kind: "Sphere",
  107387. options: options,
  107388. renderingGroupId: renderingGroupId
  107389. };
  107390. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  107391. emitterMesh.renderingGroupId = renderingGroupId;
  107392. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  107393. material.emissiveColor = options.color;
  107394. emitterMesh.material = material;
  107395. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107396. var system = _a[_i];
  107397. system.emitter = emitterMesh;
  107398. }
  107399. this._emitterNode = emitterMesh;
  107400. };
  107401. /**
  107402. * Starts all particle systems of the set
  107403. * @param emitter defines an optional mesh to use as emitter for the particle systems
  107404. */
  107405. ParticleSystemSet.prototype.start = function (emitter) {
  107406. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107407. var system = _a[_i];
  107408. if (emitter) {
  107409. system.emitter = emitter;
  107410. }
  107411. system.start();
  107412. }
  107413. };
  107414. /**
  107415. * Release all associated resources
  107416. */
  107417. ParticleSystemSet.prototype.dispose = function () {
  107418. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107419. var system = _a[_i];
  107420. system.dispose();
  107421. }
  107422. this.systems = [];
  107423. if (this._emitterNode) {
  107424. this._emitterNode.dispose();
  107425. this._emitterNode = null;
  107426. }
  107427. };
  107428. /**
  107429. * Serialize the set into a JSON compatible object
  107430. * @returns a JSON compatible representation of the set
  107431. */
  107432. ParticleSystemSet.prototype.serialize = function () {
  107433. var result = {};
  107434. result.systems = [];
  107435. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107436. var system = _a[_i];
  107437. result.systems.push(system.serialize());
  107438. }
  107439. if (this._emitterNode) {
  107440. result.emitter = this._emitterCreationOptions;
  107441. }
  107442. return result;
  107443. };
  107444. /**
  107445. * Parse a new ParticleSystemSet from a serialized source
  107446. * @param data defines a JSON compatible representation of the set
  107447. * @param scene defines the hosting scene
  107448. * @param gpu defines if we want GPU particles or CPU particles
  107449. * @returns a new ParticleSystemSet
  107450. */
  107451. ParticleSystemSet.Parse = function (data, scene, gpu) {
  107452. if (gpu === void 0) { gpu = false; }
  107453. var result = new ParticleSystemSet();
  107454. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  107455. scene = scene || BABYLON.Engine.LastCreatedScene;
  107456. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  107457. var system = _a[_i];
  107458. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  107459. }
  107460. if (data.emitter) {
  107461. var options = data.emitter.options;
  107462. switch (data.emitter.kind) {
  107463. case "Sphere":
  107464. result.setEmitterAsSphere({
  107465. diameter: options.diameter,
  107466. segments: options.segments,
  107467. color: BABYLON.Color3.FromArray(options.color)
  107468. }, data.emitter.renderingGroupId, scene);
  107469. break;
  107470. }
  107471. }
  107472. return result;
  107473. };
  107474. return ParticleSystemSet;
  107475. }());
  107476. BABYLON.ParticleSystemSet = ParticleSystemSet;
  107477. })(BABYLON || (BABYLON = {}));
  107478. //# sourceMappingURL=babylon.particleSystemSet.js.map
  107479. var BABYLON;
  107480. (function (BABYLON) {
  107481. /**
  107482. * This class is made for on one-liner static method to help creating particle system set.
  107483. */
  107484. var ParticleHelper = /** @class */ (function () {
  107485. function ParticleHelper() {
  107486. }
  107487. /**
  107488. * Create a default particle system that you can tweak
  107489. * @param emitter defines the emitter to use
  107490. * @param capacity defines the system capacity (default is 500 particles)
  107491. * @param scene defines the hosting scene
  107492. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  107493. * @returns the new Particle system
  107494. */
  107495. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  107496. if (capacity === void 0) { capacity = 500; }
  107497. if (useGPU === void 0) { useGPU = false; }
  107498. var system;
  107499. if (useGPU) {
  107500. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  107501. }
  107502. else {
  107503. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  107504. }
  107505. system.emitter = emitter;
  107506. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  107507. system.createConeEmitter(0.1, Math.PI / 4);
  107508. // Particle color
  107509. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  107510. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  107511. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  107512. // Particle Size
  107513. system.minSize = 0.1;
  107514. system.maxSize = 0.1;
  107515. // Emission speed
  107516. system.minEmitPower = 2;
  107517. system.maxEmitPower = 2;
  107518. // Update speed
  107519. system.updateSpeed = 1 / 60;
  107520. system.emitRate = 30;
  107521. return system;
  107522. };
  107523. /**
  107524. * This is the main static method (one-liner) of this helper to create different particle systems
  107525. * @param type This string represents the type to the particle system to create
  107526. * @param scene The scene where the particle system should live
  107527. * @param gpu If the system will use gpu
  107528. * @returns the ParticleSystemSet created
  107529. */
  107530. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  107531. if (gpu === void 0) { gpu = false; }
  107532. if (!scene) {
  107533. scene = BABYLON.Engine.LastCreatedScene;
  107534. ;
  107535. }
  107536. var token = {};
  107537. scene._addPendingData(token);
  107538. return new Promise(function (resolve, reject) {
  107539. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  107540. scene._removePendingData(token);
  107541. return reject("Particle system with GPU is not supported.");
  107542. }
  107543. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  107544. scene._removePendingData(token);
  107545. var newData = JSON.parse(data.toString());
  107546. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  107547. }, undefined, undefined, undefined, function (req, exception) {
  107548. scene._removePendingData(token);
  107549. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  107550. });
  107551. });
  107552. };
  107553. /**
  107554. * Static function used to export a particle system to a ParticleSystemSet variable.
  107555. * Please note that the emitter shape is not exported
  107556. * @param system defines the particle systems to export
  107557. */
  107558. ParticleHelper.ExportSet = function (systems) {
  107559. var set = new BABYLON.ParticleSystemSet();
  107560. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  107561. var system = systems_1[_i];
  107562. set.systems.push(system);
  107563. }
  107564. return set;
  107565. };
  107566. /**
  107567. * Gets or sets base Assets URL
  107568. */
  107569. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  107570. return ParticleHelper;
  107571. }());
  107572. BABYLON.ParticleHelper = ParticleHelper;
  107573. })(BABYLON || (BABYLON = {}));
  107574. //# sourceMappingURL=babylon.particleHelper.js.map
  107575. var BABYLON;
  107576. (function (BABYLON) {
  107577. /**
  107578. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  107579. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  107580. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  107581. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  107582. */
  107583. var VideoDome = /** @class */ (function (_super) {
  107584. __extends(VideoDome, _super);
  107585. /**
  107586. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  107587. * @param name Element's name, child elements will append suffixes for their own names.
  107588. * @param urlsOrVideo defines the url(s) or the video element to use
  107589. * @param options An object containing optional or exposed sub element properties
  107590. */
  107591. function VideoDome(name, urlsOrVideo, options, scene) {
  107592. var _this = _super.call(this, name, scene) || this;
  107593. _this._useDirectMapping = false;
  107594. // set defaults and manage values
  107595. name = name || "videoDome";
  107596. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  107597. options.clickToPlay = Boolean(options.clickToPlay);
  107598. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  107599. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  107600. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  107601. if (options.useDirectMapping === undefined) {
  107602. _this._useDirectMapping = true;
  107603. }
  107604. else {
  107605. _this._useDirectMapping = options.useDirectMapping;
  107606. }
  107607. _this._setReady(false);
  107608. // create
  107609. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  107610. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  107611. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  107612. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  107613. texture.onLoadObservable.addOnce(function () {
  107614. _this._setReady(true);
  107615. });
  107616. // configure material
  107617. material.useEquirectangularFOV = true;
  107618. material.fovMultiplier = 1.0;
  107619. material.opacityFresnel = false;
  107620. if (_this._useDirectMapping) {
  107621. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107622. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107623. material.diffuseTexture = texture;
  107624. }
  107625. else {
  107626. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107627. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107628. material.reflectionTexture = texture;
  107629. }
  107630. // configure mesh
  107631. _this._mesh.material = material;
  107632. _this._mesh.parent = _this;
  107633. // optional configuration
  107634. if (options.clickToPlay) {
  107635. scene.onPointerUp = function () {
  107636. _this._videoTexture.video.play();
  107637. };
  107638. }
  107639. return _this;
  107640. }
  107641. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  107642. /**
  107643. * Gets the video texture being displayed on the sphere
  107644. */
  107645. get: function () {
  107646. return this._videoTexture;
  107647. },
  107648. enumerable: true,
  107649. configurable: true
  107650. });
  107651. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  107652. /**
  107653. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107654. * Also see the options.resolution property.
  107655. */
  107656. get: function () {
  107657. return this._material.fovMultiplier;
  107658. },
  107659. set: function (value) {
  107660. this._material.fovMultiplier = value;
  107661. },
  107662. enumerable: true,
  107663. configurable: true
  107664. });
  107665. /**
  107666. * Releases resources associated with this node.
  107667. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107668. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107669. */
  107670. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107671. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107672. this._videoTexture.dispose();
  107673. this._mesh.dispose();
  107674. this._material.dispose();
  107675. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107676. };
  107677. return VideoDome;
  107678. }(BABYLON.TransformNode));
  107679. BABYLON.VideoDome = VideoDome;
  107680. })(BABYLON || (BABYLON = {}));
  107681. //# sourceMappingURL=babylon.videoDome.js.map
  107682. var BABYLON;
  107683. (function (BABYLON) {
  107684. /**
  107685. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  107686. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  107687. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  107688. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  107689. */
  107690. var PhotoDome = /** @class */ (function (_super) {
  107691. __extends(PhotoDome, _super);
  107692. /**
  107693. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  107694. * @param name Element's name, child elements will append suffixes for their own names.
  107695. * @param urlsOfPhoto defines the url of the photo to display
  107696. * @param options defines an object containing optional or exposed sub element properties
  107697. * @param onError defines a callback called when an error occured while loading the texture
  107698. */
  107699. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  107700. if (onError === void 0) { onError = null; }
  107701. var _this = _super.call(this, name, scene) || this;
  107702. _this._useDirectMapping = false;
  107703. /**
  107704. * Observable raised when an error occured while loading the 360 image
  107705. */
  107706. _this.onLoadErrorObservable = new BABYLON.Observable();
  107707. // set defaults and manage values
  107708. name = name || "photoDome";
  107709. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  107710. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  107711. if (options.useDirectMapping === undefined) {
  107712. _this._useDirectMapping = true;
  107713. }
  107714. else {
  107715. _this._useDirectMapping = options.useDirectMapping;
  107716. }
  107717. _this._setReady(false);
  107718. // create
  107719. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  107720. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  107721. // configure material
  107722. material.opacityFresnel = false;
  107723. material.useEquirectangularFOV = true;
  107724. material.fovMultiplier = 1.0;
  107725. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  107726. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  107727. if (onError) {
  107728. onError(message, exception);
  107729. }
  107730. });
  107731. _this.photoTexture.onLoadObservable.addOnce(function () {
  107732. _this._setReady(true);
  107733. });
  107734. // configure mesh
  107735. _this._mesh.material = material;
  107736. _this._mesh.parent = _this;
  107737. return _this;
  107738. }
  107739. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  107740. /**
  107741. * Gets or sets the texture being displayed on the sphere
  107742. */
  107743. get: function () {
  107744. return this._photoTexture;
  107745. },
  107746. set: function (value) {
  107747. if (this._photoTexture === value) {
  107748. return;
  107749. }
  107750. this._photoTexture = value;
  107751. if (this._useDirectMapping) {
  107752. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107753. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107754. this._material.diffuseTexture = this._photoTexture;
  107755. }
  107756. else {
  107757. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107758. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107759. this._material.reflectionTexture = this._photoTexture;
  107760. }
  107761. },
  107762. enumerable: true,
  107763. configurable: true
  107764. });
  107765. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  107766. /**
  107767. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107768. * Also see the options.resolution property.
  107769. */
  107770. get: function () {
  107771. return this._material.fovMultiplier;
  107772. },
  107773. set: function (value) {
  107774. this._material.fovMultiplier = value;
  107775. },
  107776. enumerable: true,
  107777. configurable: true
  107778. });
  107779. /**
  107780. * Releases resources associated with this node.
  107781. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107782. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107783. */
  107784. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107785. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107786. this._photoTexture.dispose();
  107787. this._mesh.dispose();
  107788. this._material.dispose();
  107789. this.onLoadErrorObservable.clear();
  107790. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107791. };
  107792. return PhotoDome;
  107793. }(BABYLON.TransformNode));
  107794. BABYLON.PhotoDome = PhotoDome;
  107795. })(BABYLON || (BABYLON = {}));
  107796. //# sourceMappingURL=babylon.photoDome.js.map
  107797. var BABYLON;
  107798. (function (BABYLON) {
  107799. BABYLON.Engine.prototype.createQuery = function () {
  107800. return this._gl.createQuery();
  107801. };
  107802. BABYLON.Engine.prototype.deleteQuery = function (query) {
  107803. this._gl.deleteQuery(query);
  107804. return this;
  107805. };
  107806. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  107807. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  107808. };
  107809. BABYLON.Engine.prototype.getQueryResult = function (query) {
  107810. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  107811. };
  107812. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  107813. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107814. this._gl.beginQuery(glAlgorithm, query);
  107815. return this;
  107816. };
  107817. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  107818. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107819. this._gl.endQuery(glAlgorithm);
  107820. return this;
  107821. };
  107822. BABYLON.Engine.prototype._createTimeQuery = function () {
  107823. var timerQuery = this.getCaps().timerQuery;
  107824. if (timerQuery.createQueryEXT) {
  107825. return timerQuery.createQueryEXT();
  107826. }
  107827. return this.createQuery();
  107828. };
  107829. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  107830. var timerQuery = this.getCaps().timerQuery;
  107831. if (timerQuery.deleteQueryEXT) {
  107832. timerQuery.deleteQueryEXT(query);
  107833. return;
  107834. }
  107835. this.deleteQuery(query);
  107836. };
  107837. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  107838. var timerQuery = this.getCaps().timerQuery;
  107839. if (timerQuery.getQueryObjectEXT) {
  107840. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  107841. }
  107842. return this.getQueryResult(query);
  107843. };
  107844. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  107845. var timerQuery = this.getCaps().timerQuery;
  107846. if (timerQuery.getQueryObjectEXT) {
  107847. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  107848. }
  107849. return this.isQueryResultAvailable(query);
  107850. };
  107851. BABYLON.Engine.prototype.startTimeQuery = function () {
  107852. var caps = this.getCaps();
  107853. var timerQuery = caps.timerQuery;
  107854. if (!timerQuery) {
  107855. return null;
  107856. }
  107857. var token = new BABYLON._TimeToken();
  107858. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107859. if (caps.canUseTimestampForTimerQuery) {
  107860. token._startTimeQuery = this._createTimeQuery();
  107861. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  107862. }
  107863. else {
  107864. if (this._currentNonTimestampToken) {
  107865. return this._currentNonTimestampToken;
  107866. }
  107867. token._timeElapsedQuery = this._createTimeQuery();
  107868. if (timerQuery.beginQueryEXT) {
  107869. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107870. }
  107871. else {
  107872. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107873. }
  107874. this._currentNonTimestampToken = token;
  107875. }
  107876. return token;
  107877. };
  107878. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  107879. var caps = this.getCaps();
  107880. var timerQuery = caps.timerQuery;
  107881. if (!timerQuery || !token) {
  107882. return -1;
  107883. }
  107884. if (caps.canUseTimestampForTimerQuery) {
  107885. if (!token._startTimeQuery) {
  107886. return -1;
  107887. }
  107888. if (!token._endTimeQuery) {
  107889. token._endTimeQuery = this._createTimeQuery();
  107890. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  107891. }
  107892. }
  107893. else if (!token._timeElapsedQueryEnded) {
  107894. if (!token._timeElapsedQuery) {
  107895. return -1;
  107896. }
  107897. if (timerQuery.endQueryEXT) {
  107898. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  107899. }
  107900. else {
  107901. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  107902. }
  107903. token._timeElapsedQueryEnded = true;
  107904. }
  107905. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107906. var available = false;
  107907. if (token._endTimeQuery) {
  107908. available = this._getTimeQueryAvailability(token._endTimeQuery);
  107909. }
  107910. else if (token._timeElapsedQuery) {
  107911. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  107912. }
  107913. if (available && !disjoint) {
  107914. var result = 0;
  107915. if (caps.canUseTimestampForTimerQuery) {
  107916. if (!token._startTimeQuery || !token._endTimeQuery) {
  107917. return -1;
  107918. }
  107919. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  107920. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  107921. result = timeEnd - timeStart;
  107922. this._deleteTimeQuery(token._startTimeQuery);
  107923. this._deleteTimeQuery(token._endTimeQuery);
  107924. token._startTimeQuery = null;
  107925. token._endTimeQuery = null;
  107926. }
  107927. else {
  107928. if (!token._timeElapsedQuery) {
  107929. return -1;
  107930. }
  107931. result = this._getTimeQueryResult(token._timeElapsedQuery);
  107932. this._deleteTimeQuery(token._timeElapsedQuery);
  107933. token._timeElapsedQuery = null;
  107934. token._timeElapsedQueryEnded = false;
  107935. this._currentNonTimestampToken = null;
  107936. }
  107937. return result;
  107938. }
  107939. return -1;
  107940. };
  107941. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  107942. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  107943. };
  107944. // We also need to update AbstractMesh as there is a portion of the code there
  107945. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  107946. var engine = this.getEngine();
  107947. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  107948. this._isOccluded = false;
  107949. return;
  107950. }
  107951. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  107952. this._isOccluded = false;
  107953. return;
  107954. }
  107955. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  107956. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  107957. if (isOcclusionQueryAvailable) {
  107958. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  107959. this._isOcclusionQueryInProgress = false;
  107960. this._occlusionInternalRetryCounter = 0;
  107961. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  107962. }
  107963. else {
  107964. this._occlusionInternalRetryCounter++;
  107965. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  107966. this._isOcclusionQueryInProgress = false;
  107967. this._occlusionInternalRetryCounter = 0;
  107968. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  107969. // if strict continue the last state of the object.
  107970. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  107971. }
  107972. else {
  107973. return;
  107974. }
  107975. }
  107976. }
  107977. var scene = this.getScene();
  107978. if (scene.getBoundingBoxRenderer) {
  107979. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  107980. if (!this._occlusionQuery) {
  107981. this._occlusionQuery = engine.createQuery();
  107982. }
  107983. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  107984. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  107985. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  107986. this._isOcclusionQueryInProgress = true;
  107987. }
  107988. };
  107989. })(BABYLON || (BABYLON = {}));
  107990. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  107991. var BABYLON;
  107992. (function (BABYLON) {
  107993. /**
  107994. * Class used to generate noise procedural textures
  107995. */
  107996. var NoiseProceduralTexture = /** @class */ (function (_super) {
  107997. __extends(NoiseProceduralTexture, _super);
  107998. /**
  107999. * Creates a new NoiseProceduralTexture
  108000. * @param name defines the name fo the texture
  108001. * @param size defines the size of the texture (default is 256)
  108002. * @param scene defines the hosting scene
  108003. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  108004. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  108005. */
  108006. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  108007. if (size === void 0) { size = 256; }
  108008. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  108009. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  108010. _this._time = 0;
  108011. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  108012. _this.brightness = 0.2;
  108013. /** Defines the number of octaves to process */
  108014. _this.octaves = 3;
  108015. /** Defines the level of persistence (0.8 by default) */
  108016. _this.persistence = 0.8;
  108017. /** Gets or sets animation speed factor (default is 1) */
  108018. _this.animationSpeedFactor = 1;
  108019. _this._updateShaderUniforms();
  108020. return _this;
  108021. }
  108022. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  108023. var scene = this.getScene();
  108024. if (!scene) {
  108025. return;
  108026. }
  108027. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  108028. this.setFloat("brightness", this.brightness);
  108029. this.setFloat("persistence", this.persistence);
  108030. this.setFloat("timeScale", this._time);
  108031. };
  108032. NoiseProceduralTexture.prototype._getDefines = function () {
  108033. return "#define OCTAVES " + this.octaves;
  108034. };
  108035. /** Generate the current state of the procedural texture */
  108036. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  108037. this._updateShaderUniforms();
  108038. _super.prototype.render.call(this, useCameraPostProcess);
  108039. };
  108040. /**
  108041. * Serializes this noise procedural texture
  108042. * @returns a serialized noise procedural texture object
  108043. */
  108044. NoiseProceduralTexture.prototype.serialize = function () {
  108045. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  108046. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  108047. return serializationObject;
  108048. };
  108049. /**
  108050. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  108051. * @param parsedTexture defines parsed texture data
  108052. * @param scene defines the current scene
  108053. * @param rootUrl defines the root URL containing noise procedural texture information
  108054. * @returns a parsed NoiseProceduralTexture
  108055. */
  108056. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  108057. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  108058. return texture;
  108059. };
  108060. return NoiseProceduralTexture;
  108061. }(BABYLON.ProceduralTexture));
  108062. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  108063. })(BABYLON || (BABYLON = {}));
  108064. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  108065. var __assign = (this && this.__assign) || function () {
  108066. __assign = Object.assign || function(t) {
  108067. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108068. s = arguments[i];
  108069. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108070. t[p] = s[p];
  108071. }
  108072. return t;
  108073. };
  108074. return __assign.apply(this, arguments);
  108075. };
  108076. var BABYLON;
  108077. (function (BABYLON) {
  108078. /**
  108079. * This can helps recording videos from BabylonJS.
  108080. * This is based on the available WebRTC functionalities of the browser.
  108081. *
  108082. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  108083. */
  108084. var VideoRecorder = /** @class */ (function () {
  108085. /**
  108086. * Create a new VideoCapture object which can help converting what you see in Babylon to
  108087. * a video file.
  108088. * @param engine Defines the BabylonJS Engine you wish to record
  108089. * @param options Defines options that can be used to customized the capture
  108090. */
  108091. function VideoRecorder(engine, options) {
  108092. if (options === void 0) { options = null; }
  108093. if (!VideoRecorder.IsSupported(engine)) {
  108094. throw "Your browser does not support recording so far.";
  108095. }
  108096. var canvas = engine.getRenderingCanvas();
  108097. if (!canvas) {
  108098. throw "The babylon engine must have a canvas to be recorded";
  108099. }
  108100. this._canvas = canvas;
  108101. this._canvas.isRecording = false;
  108102. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  108103. var stream = this._canvas.captureStream(this._options.fps);
  108104. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  108105. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  108106. this._mediaRecorder.onerror = this._handleError.bind(this);
  108107. this._mediaRecorder.onstop = this._handleStop.bind(this);
  108108. }
  108109. /**
  108110. * Returns wehther or not the VideoRecorder is available in your browser.
  108111. * @param engine Defines the Babylon Engine to check the support for
  108112. * @returns true if supported otherwise false
  108113. */
  108114. VideoRecorder.IsSupported = function (engine) {
  108115. var canvas = engine.getRenderingCanvas();
  108116. return (!!canvas && typeof canvas.captureStream === "function");
  108117. };
  108118. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  108119. /**
  108120. * True wether a recording is already in progress.
  108121. */
  108122. get: function () {
  108123. return !!this._canvas && this._canvas.isRecording;
  108124. },
  108125. enumerable: true,
  108126. configurable: true
  108127. });
  108128. /**
  108129. * Stops the current recording before the default capture timeout passed in the startRecording
  108130. * functions.
  108131. */
  108132. VideoRecorder.prototype.stopRecording = function () {
  108133. if (!this._canvas || !this._mediaRecorder) {
  108134. return;
  108135. }
  108136. if (!this.isRecording) {
  108137. return;
  108138. }
  108139. this._canvas.isRecording = false;
  108140. this._mediaRecorder.stop();
  108141. };
  108142. /**
  108143. * Starts recording the canvas for a max duration specified in parameters.
  108144. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  108145. * @param maxDuration Defines the maximum recording time in seconds.
  108146. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  108147. * @return a promise callback at the end of the recording with the video data in Blob.
  108148. */
  108149. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  108150. var _this = this;
  108151. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  108152. if (maxDuration === void 0) { maxDuration = 7; }
  108153. if (!this._canvas || !this._mediaRecorder) {
  108154. throw "Recorder has already been disposed";
  108155. }
  108156. if (this.isRecording) {
  108157. throw "Recording already in progress";
  108158. }
  108159. if (maxDuration > 0) {
  108160. setTimeout(function () {
  108161. _this.stopRecording();
  108162. }, maxDuration * 1000);
  108163. }
  108164. this._fileName = fileName;
  108165. this._recordedChunks = [];
  108166. this._resolve = null;
  108167. this._reject = null;
  108168. this._canvas.isRecording = true;
  108169. this._mediaRecorder.start(this._options.recordChunckSize);
  108170. return new Promise(function (resolve, reject) {
  108171. _this._resolve = resolve;
  108172. _this._reject = reject;
  108173. });
  108174. };
  108175. /**
  108176. * Releases internal resources used during the recording.
  108177. */
  108178. VideoRecorder.prototype.dispose = function () {
  108179. this._canvas = null;
  108180. this._mediaRecorder = null;
  108181. this._recordedChunks = [];
  108182. this._fileName = null;
  108183. this._resolve = null;
  108184. this._reject = null;
  108185. };
  108186. VideoRecorder.prototype._handleDataAvailable = function (event) {
  108187. if (event.data.size > 0) {
  108188. this._recordedChunks.push(event.data);
  108189. }
  108190. };
  108191. VideoRecorder.prototype._handleError = function (event) {
  108192. this.stopRecording();
  108193. if (this._reject) {
  108194. this._reject(event.error);
  108195. }
  108196. else {
  108197. throw new event.error;
  108198. }
  108199. };
  108200. VideoRecorder.prototype._handleStop = function () {
  108201. this.stopRecording();
  108202. var superBuffer = new Blob(this._recordedChunks);
  108203. if (this._resolve) {
  108204. this._resolve(superBuffer);
  108205. }
  108206. window.URL.createObjectURL(superBuffer);
  108207. if (this._fileName) {
  108208. BABYLON.Tools.Download(superBuffer, this._fileName);
  108209. }
  108210. };
  108211. VideoRecorder._defaultOptions = {
  108212. mimeType: "video/webm",
  108213. fps: 25,
  108214. recordChunckSize: 3000
  108215. };
  108216. return VideoRecorder;
  108217. }());
  108218. BABYLON.VideoRecorder = VideoRecorder;
  108219. })(BABYLON || (BABYLON = {}));
  108220. //# sourceMappingURL=babylon.videoRecorder.js.map
  108221. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  108222. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  108223. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  108224. globalObject["BABYLON"] = BABYLON;
  108225. //backwards compatibility
  108226. if(typeof earcut !== 'undefined') {
  108227. globalObject["Earcut"] = {
  108228. earcut: earcut
  108229. };
  108230. }
  108231. return BABYLON;
  108232. });